python 中的strptime()和strftime()

python 中的strptime()和strftime()

转自:https://blog.csdn.net/qq_39348113/article/details/82528851

strptime():
功能:按照特定时间格式将字符串转换(解析)为时间类型。
示例如下:

def date_try(date):
date = datetime.datetime.strptime(date,'%Y-%m-%d')
return date

def main():
a = date_try('2016-02-29')
print(a)

main()
1
2
3
4
5
6
7
8
9
输出如下:

2016-02-29 00:00:00

Process finished with exit code 0
1
2
3
可见,在这段代码中,strptime()函数将字符串‘2016-02-29’解析为时间。
如果我将这段字符串改为‘2016-02-30’后,超出了2月份的天数极限,运行就会报错

def date_try(date):
date = datetime.datetime.strptime(date,'%Y-%m-%d')
return date

def main():
a = date_try('2016-02-30')
print(a)

main()
1
2
3
4
5
6
7
8
9
10
运行报错如下:


ValueError: day is out of range for month

Process finished with exit code 1
1
2
3
4
5
strftime()功能如下:
将你需要的时间格式化为自己需要的格式。

def date_try(date):
date = datetime.datetime.strptime(date,'%Y-%m-%d')
return date

def main():
a = date_try('2016-02-29')
print(a)
b = a.strftime('%Y-%m-%d')
print(b)

main()
1
2
3
4
5
6
7
8
9
10
11
输出如下:

2016-02-29 00:00:00
2016-02-29

Process finished with exit code 0
————————————————
版权声明:本文为CSDN博主「集音」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_39348113/article/details/82528851

猜你喜欢

转载自www.cnblogs.com/sophe/p/11533908.html