英文:
Finding correct strftime format dynamically?
问题
from datetime import datetime, timedelta, date
DateTime = "2021-05-25T13:52:50.980437-04:00"
String_Format = '%Y-%m-%dT%H:%M:%S%z'
Error Message:
time data '2021-05-25T13:52:50.980437-04:00' does not match format '%Y-%m-%dT%H:%M:%S%z'
如何可靠地确定任何进入我的数据集的日期时间格式?
英文:
from datetime import datetime, timedelta, date
DateTime = "2021-05-25T13:52:50.980437-04:00"
String_Format = '%Y-%m-%dT%H:%M:%S%z'
Error Message:
> time data '2021-05-25T13:52:50.980437-04:00' does not match format '%Y-%m-%dT%H:%M:%S%z'
How can I reliably figure out the datetime formats for any datetime format that comes into my data sets?
答案1
得分: 1
尝试在循环中检查几种已知的格式
from datetime import datetime
def parse(v):
for fmt in ('%Y-%m-%dT%H:%M:%S%z', '%Y-%m-%dT%H:%M:%S.%f%z'):
try:
return datetime.strptime(v, fmt)
except ValueError as e:
continue
raise e
parse('2021-05-25T13:52:50.980437-04:00')
此外,在您的特定示例中,您缺少%f
。
英文:
try checking several known formats in a loop
from datetime import datetime
def parse(v):
for fmt in ('%Y-%m-%dT%H:%M:%S%z', '%Y-%m-%dT%H:%M:%S.%f%z'):
try:
return datetime.strptime(v, fmt)
except ValueError as e:
continue
raise e
parse('2021-05-25T13:52:50.980437-04:00')
also, in your particular example, you are missing %f
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论