一、string time datetime之间的相互转换
1、string->time
>>> time.strptime('2012-08-04', '%Y-%m-%d')
time.struct_time(tm_year=2012, tm_mon=8, tm_mday=4, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=217, tm_isdst=-1)
time.struct_time(tm_year=2012, tm_mon=8, tm_mday=4, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=217, tm_isdst=-1)
2、time->string
>>> import time
#方法1
>>> time.strftime('%Y-%m-%d', time.localtime()) #'2012-08-04'
>>> time.strftime('%Y-%m-%d', time.localtime()) #'2012-08-04'
#方法2
>>> time.strftime('%Y-%m-%d', time.localtime(time.time())) #'2012-08-04'
>>> time.strftime('%Y-%m-%d', time.localtime(time.time())) #'2012-08-04'
其中strftime(应该是string format time的意思)用来格式化时间,第一个参数为格式化字符串,第二个参数为一个结构体struct,而time.time()函数则是获取机器时间
3、string -> datetime
#方法1
按string->time->datetime进行转化
>>> import datetime
>>> datetime.datetime(*time.strptime('2012-08-04', '%Y-%m-%d')[:3]) #datetime.datetime(2012, 8, 4, 0, 0)
>>> datetime.datetime(*time.strptime('2012-08-04', '%Y-%m-%d')[:3]) #datetime.datetime(2012, 8, 4, 0, 0)
#方法2
>>> import datetime
>>>
datetime.datetime.strptime('2012-08-04', '%Y-%m-%d') #datetime.datetime(2012, 8, 4, 0, 0)
4、datetime -> string
>>> import datetime
>>> now = time.localtime()
>>> dt = datetime.datetime(*now[:3])
#按指定的格式返回字符串
>>> dt.
strftime(format='%Y-%m-%d') #'2012-08-04'
#默认格式返回字符串
>>> dt.
ctime() #'Sat Aug 4 00:00:00 2012'
5、time -> datetime
>>> import datetime
>>> now = time.localtime()
>>> now = time.localtime()
>>> datetime.datetime(*now[:3]) #datetime.datetime(2012, 8, 4, 0, 0)
6、datetime -> time
>>> dt.
timetuple()
输出:time.struct_time(tm_year=2012, tm_mon=8, tm_mday=4, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=217, tm_isdst=-1)
输出:time.struct_time(tm_year=2012, tm_mon=8, tm_mday=4, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=217, tm_isdst=-1)
二、datetime的计算
datetime的加减会涉及
timedelta
1、时间相减
>>> dt1 = datetime.datetime(2012, 8, 4, 20, 33, 34)
>>> dt2 = datetime.datetime(2012, 7, 5, 14, 22, 32)
>>> dt1-dt2 #datetime.timedelta(30, 22262)
>>> dt2 = datetime.datetime(2012, 7, 5, 14, 22, 32)
>>> dt1-dt2 #datetime.timedelta(30, 22262)
>>> (dt1-dt2).days #30
2、一段时间之后或之前
>>> dt1+datetime.timedelta(days=10) #datetime.datetime(2012, 8, 14, 20, 33, 34)
>>> dt1-datetime.timedelta(days=10) #datetime.datetime(2012, 7, 25, 20, 33, 34)
>>> dt4 = datetime.date(2012, 8, 14)
>>> dt5 = datetime.date(2012, 7, 22)
>>> dt4-dt5 #datetime.timedelta(23)
>>> dt5 = datetime.date(2012, 7, 22)
>>> dt4-dt5 #datetime.timedelta(23)