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