3

2022-02-18T00:00:00.000Z in this string is the information that this time is 07:00 PM with this being eastern time (ET), which appears correct as ET is 5 hours behind UTC. How can we (a) first convert from string to (datetime?, timestamp?), and then convert the resulting time object into 07:00 PM? What has been tried:

from datetime import datetime
datetime.strptime('2022-02-18T00:00:00.000Z', '%Y-%m-%dT%H:%M:%S.%f')

...which throws the error time data '2022-02-18T00:00:00.000Z' does not match format '%Y-%m-%d %H:%M:%S.%f'. What is being done wrong here?

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
Canovice
  • 9,012
  • 22
  • 93
  • 211
  • 1
    you are missing a Z. `'%Y-%m-%dT%H:%M:%S.%fZ'` –  Feb 17 '22 at 16:33
  • 2
    You could also include the timezone in the parsing by doing: `'%Y-%m-%dT%H:%M:%S.%f%z'` which would give you the output: `datetime.datetime(2022, 2, 18, 0, 0, tzinfo=datetime.timezone.utc)`. – hoboman Feb 17 '22 at 16:36
  • 2
    Does this answer your question? [How do I parse an ISO 8601-formatted date?](https://stackoverflow.com/questions/127803/how-do-i-parse-an-iso-8601-formatted-date) – Woodford Feb 17 '22 at 16:36
  • it doesn't get me quite all the way to `07:00 PM` – Canovice Feb 17 '22 at 16:43
  • `datetime.fromisoformat('2022-02-18T00:00:00.000Z'.replace('Z', '+00:00')).strftime('%I:%M %p')`? You might as well strip the Z if you don't care about the time zone (UTC). – FObersteiner Feb 17 '22 at 16:46
  • We are looking for it to be eastern time zone, this is great but it does return UTC time zone – Canovice Feb 17 '22 at 16:47
  • then parse *with* the Z and add `.astimezone(ZoneInfo('America/New_York'))` prior to strftime with ZoneInfo class from zoneinfo module. Now that's becoming multiple questions in one... – FObersteiner Feb 17 '22 at 16:49
  • okay got it, yeah `datetime.strptime('2022-02-18T00:00:00.000Z', '%Y-%m-%dT%H:%M:%S.%fZ').astimezone(ZoneInfo('America/New_York')).strftime('%I:%M %p')` gets me very close, although it is returning 6PM instead of 7PM, seems like perhaps something with daylight savings is off. – Canovice Feb 17 '22 at 16:53
  • 1
    Do not use a literal Z ! Use `%z`. Z *ignores* the time zone / UTC – FObersteiner Feb 17 '22 at 16:53

1 Answers1

9

Summarizing everything from the comments above:

datetime.strptime('2022-02-18T00:00:00.000Z', '%Y-%m-%dT%H:%M:%S.%f%z').astimezone(ZoneInfo('America/New_York')).strftime('%I:%M %p')

returns exactly what we needed.

Canovice
  • 9,012
  • 22
  • 93
  • 211