Python时间相关的操作

与时间相关的包大概有datetime和time这两个。

>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2018, 5, 16, 16, 37, 15, 77192)
>>> type(now)

>>> now = time.time()
>>> type(now)

>>> now
1526459947.3928223
>>> time.localtime(now) 传入一个unix时间戳
time.struct_time(tm_year=2018, tm_mon=5, tm_mday=16, tm_hour=16, tm_min=39, tm_sec=7, tm_wday=2, tm_yday=136, tm_isdst=0)
>>> type(time.localtime(now))

datetime.now()得到的是datetime类型的对象,time.time()得到的是一个unix时间戳,也就是一个浮点数。time.localtime得到的是一个struct_time类型的对象。

>>> d = datetime.datetime.now()
>>> d
datetime.datetime(2018, 5, 16, 16, 48, 28, 8122)
>>> (d.year, d.month, d.day, d.hour)
(2018, 5, 16, 16)
>>> now = time.time()
>>> t = time.localtime(now)
>>> t
time.struct_time(tm_year=2018, tm_mon=5, tm_mday=16, tm_hour=17, tm_min=9, tm_sec=24, tm_wday=2, tm_yday=136, tm_isdst=0)
>>> (t.tm_year, t.tm_mon) 
(2018, 5)

datetime和struct_time类型都可以很容易的得到年月日。
这几个类型可以相互转化。

>>> datetime.datetime.now().timetuple() // datetime转time_struct
time.struct_time(tm_year=2018, tm_mon=5, tm_mday=16, tm_hour=17, tm_min=13, tm_sec=15, tm_wday=2, tm_yday=136, tm_isdst=-1)
>>> time.mktime(datetime.datetime.now().timetuple()) // datetime转time_struct再转unix时间戳
1526462212.0
>>> datetime.datetime.fromtimestamp(time.time()) // unix时间戳转datetime
datetime.datetime(2018, 5, 16, 17, 18, 30, 84841)

你可能感兴趣的:(Python时间相关的操作)