嗨,我正在尝试转换以下时间格式
2020-08-28T13:42:00.298363-05:00
到
28-Sept-2020
我正在使用以下代码,但是它不起作用。
from datetime import datetime
start_time = "2020-08-28T13:42:00.298363-05:00"
start_period_obj = datetime.strptime(start_time, "%Y-%m-%dT%H:%M:%f.%-s-%z)
print(start_period_obj)
输出为
File "time conveter.py", line 19
start_period_obj = datetime.strptime(start_time, "%Y-%m-%dT%H:%M:%f.%-s-%z)
^
SyntaxError: EOL while scanning string literal
答案 0 :(得分:0)
您的代码缺少日期时间格式字符串末尾的右引号,这会导致您看到错误消息。正如@ChrisCharley指出的那样,实际格式字符串也有问题
此start_period_obj = datetime.strptime(start_time, "%Y-%m-%dT%H:%M:%f.%-s-%z)
应该为start_period_obj = datetime.strptime(start_time, "%Y-%m-%dT%H:%M:%S.%f%z")
要生成所需的格式,可以使用:
start_period_obj.strftime("%d-%b-%Y")
有关完整详细信息,请参见此处https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
答案 1 :(得分:0)
尝试一下:
from datetime import datetime
start_time = "2020-08-28T13:42:00.298363-05:00"
#removing the time information since, you don't want in the final output anyway
start_time = start_time.split('T')[0]
start_period_obj = datetime.strptime(start_time, "%Y-%m-%d")
start_period_obj = start_period_obj.strftime("%d-%b-%Y")
print(start_period_obj)
或者这一个班轮:
start_period_obj = datetime.strptime(start_time.split('T')[0], "%Y-%m-%d").strftime("%d-%b-%Y")
print(start_period_obj)
输出:
'28-Aug-2020'