找到动态的正确strftime格式?

huangapple go评论68阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年2月27日 12:30:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75576790.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定