import time
if __name__ == "__main__":print dir(time)'''['__doc__', '__name__', '__package__', 'accept2dyear', 'altzone', 'asctime', 'clock', 'ctime', \'daylight', 'gmtime', 'localtime', 'mktime', 'sleep', 'strftime', 'strptime', 'struct_time', \'time', 'timezone', 'tzname', 'tzset']'''print "时间戳 t:",time.time() print "%Y-%m-%d %H:%M:%S",time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) print "%b %d(%a) %Y %H:%M:%S ",time.strftime("%b %d(%a) %Y %H:%M:%S", time.localtime()) str_time = "2018-08-21 15:20:33"stamp_time = time.mktime(time.strptime(str_time,"%Y-%m-%d %H:%M:%S"))print "stamp:", stamp_time,"type:",type(stamp_time) newstr_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(stamp_time))print "new string:", newstr_time array_time = time.strptime(str_time, "%Y-%m-%d %H:%M:%S")print "Array:",array_time ,"type:",type(array_time) '''Array: time.struct_time(tm_year=2018, tm_mon=8, tm_mday=21, tm_hour=15, tm_min=20,tm_sec=33, tm_wday=1, tm_yday=233, tm_isdst=-1) type: time.struct_time'>'''newstr_time2 = time.strftime("%Y-%m-%d %H:%M:%S",array_time )print "new string2:",newstr_time2 print "当前的CPU时间:", time.clock()
上面介绍了python time模块的简单、常用的介绍。但是,作为python 一定还有更简单更方便使用的模块,例如arrow。
可以认为 Arrow 对象是一个增强版的 datetime 对象。
>>> import arrow>>> arrow.now()
2018-08-24T07:09:03.468562+08:00]>>>> arrow.utcnow()
2018-08-23T23:11:50.147585+00:00]>>>> type(arrow.now().datetime)
'datetime.datetime'>>>> arrow.now().timestamp
1535602673>>> arrow.now().date()
datetime.date(2018, 8, 30)>>> arrow.now().time()
datetime.time(12, 19, 52, 594274)>>> a = arrow.now()
>>> a.year
2018
>>> a.month
8
>>> a.day
30
>>> a.hour
11
>>> a.shift(months=-1)
2018-07-30T14:21:09.975506+08:00]>
>>> a.shift(months=-1).format("YYYYMM")
u'201807'
>>> a.shift(years=1).format("YYYYMM")
u'201908'
>>> a.shift(hours=-8).format("YYYYMMDD,hh:mm:ss")
u'20180830,06:21:09'
a.shift(weeks=1).format("YYYYMMDD,hh:mm:ss (d)")
u'20180906,02:21:09 (4)'获取arrow对象的创建时间,并直接表达:
>>> a = arrow.now()
>>> a.humanize()
u'just now'
>>> a.humanize()
u'9 minutes ago'
>>> t=arrow.now()
>>> t
2018-08-30T15:02:44.008442+08:00]>
>>> t.format("YYYY-MM-DD HH:mm:ss (d)")
u'2018-08-30 15:02:44 (4)'
>>> t.to("utc").format("YYYY-MM-DD HH:mm:ss (d)")
u'2018-08-30 07:02:44 (4)'
>>> t.to("America/New_York").format("YYYY-MM-DD HH:mm:ss (d)")
u'2018-08-30 03:02:44 (4)'
t = arrow.get(1535613987)
>>> t.format("YYYY-MM-DD HH:mm:ss")
u'2018-08-30 07:26:27'
import datetime
>>> arrow.get(datetime.date(2018,5,12))
2018-05-12T00:00:00+00:00]>
>>> arrow.get(datetime.date(2018,5,12)).format("YYYY-MM-DD")
u'2018-05-12'
arrow.get("2017-05-19 23:59:59","YYYY-MM-DD HH:mm:ss")
2017-05-19T23:59:59+00:00]>
>>> arrow.get("2017-05-19 23:59:59","YYYY-MM-DD HH:mm:ss")
2017-05-19T23:59:59+00:00]>
格式:
更多:
官方文档
GitHub