如何将字符串转换为datetime
在python中对于时间和字符串之间的转换很常见,但是具体是怎么实现的,如何将字符串转换为datetime呢?
案例:time & datetime & string 相互转换
#!/usr/bin/env python# -*- coding:utf-8 -*-import datetimeimport time# 日期时间字符串st = "2017-11-23 16:10:10"# 当前日期时间dt = datetime.datetime.now()# 当前时间戳sp = time.time()# 1.把datetime转成字符串def datetime_toString(dt): print("1.把datetime转成字符串: ", dt.strftime("%Y-%m-%d %H:%M:%S"))# 2.把字符串转成datetimedef string_toDatetime(st): print("2.把字符串转成datetime: ", datetime.datetime.strptime(st, "%Y-%m-%d %H:%M:%S"))# 3.把字符串转成时间戳形式def string_toTimestamp(st): print("3.把字符串转成时间戳形式:", time.mktime(time.strptime(st, "%Y-%m-%d %H:%M:%S")))# 4.把时间戳转成字符串形式def timestamp_toString(sp): print("4.把时间戳转成字符串形式: ", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(sp)))# 5.把datetime类型转外时间戳形式def datetime_toTimestamp(dt): print("5.把datetime类型转外时间戳形式:", time.mktime(dt.timetuple()))# 1.把datetime转成字符串datetime_toString(dt)# 2.把字符串转成datetimestring_toDatetime(st)# 3.把字符串转成时间戳形式string_toTimestamp(st)# 4.把时间戳转成字符串形式timestamp_toString(sp)# 5.把datetime类型转外时间戳形式datetime_toTimestamp(dt)
实验结果:
1.把datetime转成字符串: 2017-11-23 17:05:18
2.把字符串转成datetime: 2017-11-23 16:10:10
3.把字符串转成时间戳形式: 1511424610.0
4.把时间戳转成字符串形式: 2017-11-23 17:05:18
5.把datetime类型转外时间戳形式: 1511427918.0