Search code examples
pythondatetimepython-datetime

How i convert email receiving date to date and time


Email receiving date is

2022-01-22 10:01:02

Date extract from email header it show:

2022-01-22 03:01:02-06:00

I need help to convert email header date 2022-01-22 03:01:02-06:00 to datetime.datetime(2022, 01, 22, 10, 01, 02, tzinfo=<UTC>)


Solution

  • datetime.datetime.fromisoformat() works, so no need to define your own .strptime. Just do the timezone conversion after the datetime object is created:

    import datetime
    
    s = "2022-01-22 03:01:02-06:00"
    
    dt = datetime.datetime.fromisoformat(s).astimezone(datetime.timezone.utc)
    print(dt)