0
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?

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
Matthew Metros
  • 243
  • 1
  • 3
  • 10
  • 1
    Automatically? You can't. There are too many variations. Consider 12/12/12. Which one is the month, which is the day, which is the year? – Tim Roberts Feb 27 '23 at 04:35
  • 1
    Besides, you're looking for a parsing directive for `strptime`; strftime is for conversion of datetime object to string. And for standardized formats as the one you show, there's [datetime.fromisoformat](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat). – FObersteiner Feb 27 '23 at 07:11
  • related: [Datetime conversion - How to extract the inferred format?](https://stackoverflow.com/q/46842793/10197418) – FObersteiner Feb 27 '23 at 09:03

1 Answers1

1

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

ykhrustalev
  • 604
  • 10
  • 18