Python字符串与时间相互转换
1、字符串转日期/时间
注意,字符串格式要与参数中时间格式要**严格匹配**,否则异常
举例:
① 2019-05-01 12:00:00 对应 %Y-%m-%d %H:%M:%S
② 2019-05-01 对应 %Y-%m-%d
2、日期/时间转字符串
3、打印系统当前时间
代码如下:
# coding:utf-8
import datetime
import time
# 1.字符串转日期
detester = '2019-05-01'
date = datetime.datetime.strptime(detester, '%Y-%m-%d')
print(date)
# 2.日期转字符串
date = datetime.datetime.now()
print(date)
detester = date.strftime('%Y-%m-%d')
print(detester)
# 3.打印当前时间
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(current_time)
detester = date.strftime('%Y-%m-%d %H:%M:%S')
print(detester)
还没有评论,来说两句吧...