首页 > 解决方案 > Python strptime() 格式不正确

问题描述

当我尝试将字符串转换为日期时间时,它给了我一个意外的返回值。

我在运行 Python 3.7.3 的 OS X 上

我拥有的代码:

import datetime

# I have confirmed the value of this var to be {str} '01/01/2020'
effective_date = request_body.get('effective_date', None) 
effective_date1 = datetime.datetime.strptime(effective_date, "%m/%d/%Y") # returns '2020-01-01 00:00:00'

当我在我的应用程序中运行此代码时,我得到:

ValueError: time data '2020-01-01T00:00:00' does not match format '%m/%d/%Y'

标签: python-3.xstringdatetimestrptime

解决方案


我不确定您在寻找什么,但我认为这可能会有所帮助

effective_date1 = datetime.datetime.strptime(effective_date, "%m/%d/%Y").date() # returns '2020-01-01'

print(effective_date1.strftime("%x")) # now prints 01/01/20

推荐阅读