Python 时间模块time常用操作

time模块---->时间的获取和转换

time模块提供各种时间相关的功能

下面列举一些常用的操作

获取时间戳

timestamp = time.time()
print "时间戳:",timestamp
# 时间戳: 1540985031.5

获取当地时间

localtime = time.localtime()
print "当地时间",localtime
# 当地时间 time.struct_time(tm_year=2018, tm_mon=10, tm_mday=31,
# tm_hour=19, tm_min=24, tm_sec=41, tm_wday=2, tm_yday=304, tm_isdst=0)

时间转换字符串

print time.strftime('%Y-%m-%d %H:%M:%S',localtime)
# 2018-10-31 19:26:43

语法格式

time.strftime(format,dt)  dt为具体时间,datetime和date格式均可,甚至可以为时间数组struct_time
或者
dt.strftime(format)
format 可以取"%Y-%m-%d %H:%M:%S"的任意子串,来决定显示年月日时分秒

字符串转换时间语法格式

datetime.datetime.strptime(detestr,format)  datestr为字符串
format 可以取"%Y-%m-%d %H:%M:%S"的任意子串,来决定生成的时间格式

参考资料:

time模块简介和相关的专业术语

https://www.cnblogs.com/renpingsheng/p/6965044.html

https://blog.csdn.net/cm786526/article/details/79877847

猜你喜欢

转载自www.cnblogs.com/fixdq/p/9885405.html