how do you format a timestamp?

As python doens’t have fantastic timezone support out of the box I’d recommend the pytz library for this use case.

from datetime import datetime
import pytz

# Input
datetime_str = '2020-11-03T21:32:19.722012+00:00'
timezone_str = 'America/New_York'
output_format = '%m/%d/%Y %H:%M %Z'

# Convert input datetime str to python datetime obj
# this datetime is timezone aware, with tz=UTC
utc_datetime = datetime.fromisoformat(datetime_str)

# Convert input timezone str to a pytz timezone object
new_timezone = pytz.timezone(timezone_str)

# Adjust the UTC datetime to use the new timezone
new_timezone_datetime = utc_datetime.astimezone(new_timezone)

# Print in the desired output format
print(new_timezone_datetime.strftime(output_format))

If I run the above code, I get the following…

11/03/2020 16:32 EST

EDIT: The reason it is 16:32 instead of 17:32 is because American/New_York is the same as US/Eastern, in that they use EST/EDT at different points during the year (daylight savings). 2020-11-03 happens to fall in EST.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top