python進行時間和秒的轉換

1不帶年月日


# timeItv.py
# encoding:gb2312

import sys,re

# 將計時器"時:分:秒"字符串轉換爲秒數間隔
def time2itv(sTime):

    p="^([0-9]+):([0-5][0-9]):([0-5][0-9])$"
    cp=re.compile(p)
    try:
    	mTime=cp.match(sTime)
    except TypeError:
    	return "[InModuleError]:time2itv(sTime) invalid argument type"

    if mTime:
		t=map(int,mTime.group(1,2,3))
		return 3600*t[0]+60*t[1]+t[2]
    else:
    	return "[InModuleError]:time2itv(sTime) invalid argument value"


# 將秒數間隔轉換爲計時器"時:分:秒"字符串
def itv2time(iItv):

	if type(iItv)==type(1):
		h=iItv/3600
		sUp_h=iItv-3600*h
		m=sUp_h/60
		sUp_m=sUp_h-60*m
		s=sUp_m
		return ":".join(map(str,(h,m,s)))
	else:
		return "[InModuleError]:itv2time(iItv) invalid argument type"


if __name__=="__main__":
	# 僅供測試
	sTime="1223:34:15"
	itv=time2itv(sTime)
	print itv               # 4404855
	print itv2time(itv)     # 1223:34:15

	# 不合約定的參數
	print time2itv("12:34:95")
	print time2itv("sfa123")
	print time2itv(itv)

	print itv2time("451223")
	print itv2time(sTime)



題目內容:

接收用戶輸入的一個秒數(非負整數),摺合成小時、分鐘和秒輸出。


輸入格式:

一個非負整數


輸出格式:

將小時、分鐘、秒輸出到一行,中間使用空格分隔。


輸入樣例:

70000


輸出樣例:

19 26 40

時間限制:500ms內存限制:32000kb
s = int(raw_input())
h = s /3600
m =( s - h * 3600) / 60
ss = s - h * 3600 - m * 60
print str(h)+' '+str(m)+' ' + str(ss) 



2 帶年份的

#!/usr/bin/env python
# -*- coding: cp936 -*-

import time
import datetime

def ISOString2Time( s ):
    ''' 
    convert a ISO format time to second
    from:2006-04-12 16:46:40 to:23123123
    把一個時間轉化爲秒
    '''
    d=datetime.datetime.strptime(s,"%Y-%m-%d %H:%M:%S")
    return time.mktime(d.timetuple())

def Time2ISOString( s ):
    ''' 
    convert second to a ISO format time
    from: 23123123 to: 2006-04-12 16:46:40
    把給定的秒轉化爲定義的格式
    '''
    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime( float(s) ) ) 

if __name__ == '__main__':
    a="2013-08-26 16:58:00"
    b=ISOString2Time(a)
    print b
    c=Time2ISOString(b)
    print c


運行結果:

1377507480.0

2013-08-26 16:58:00


http://www.xinghaixu.com/archives/685
發佈了76 篇原創文章 · 獲贊 64 · 訪問量 36萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章