python datatime字符串和日期转换


前言

本文为了达到字符串转日期的功能,特意写博文,以供下次使用


一、datatime日期格式

python中时间日期格式化符号:

%y 两位数的年份

%Y 四位数的年份

%m 月份

%d 天

%H 24小时制小时

%I 12小时制小时

%M 分钟

%S 秒

%j 年内的一天(001-366)

一般都是:‘%Y-%m-%d-%H-%M-%S’ 代表了2022-06-17-16-55-35

二、使用步骤


from datetime import datetime
import time

date_string = '2001-06-17-00-00-00'
date_string2 = '2022-06-15-15-45-16'
#字符串转时间
date_object = datetime.strptime(date_string, '%Y-%m-%d-%H-%M-%S')
date_object2 = datetime.strptime(date_string2, '%Y-%m-%d-%H-%M-%S')
sub_time=date_object2-date_object
#获得两个时间相差秒数
print(sub_time.seconds)

#把其中一个时间前进20S
date_object=datetime.fromtimestamp( int(time.mktime(date_object.timetuple()))+20)
sub_time=date_object2-date_object
print(sub_time)
print(sub_time.seconds)


#还有一个时间转字符串的
print(date_object.strftime("%Y-%m-%d-%H-%M-%S"))


总结

简单写写,凑合着用,以后遇到其他的了,再继续补充

猜你喜欢

转载自blog.csdn.net/qq_55542491/article/details/125355418