Python Datetime : use strftime() with a timezone-aware date

Question:

Suppose I have date d like this :

>>> d 
datetime(2009, 4, 19, 21, 12, tzinfo=tzoffset(None, -7200))

As you can see, it is “timezone aware”, there is an offset of 2 Hour, utctime is

>>> d.utctimetuple() 
time.struct_time(tm_year=2009, tm_mon=4, tm_mday=19, 
                 tm_hour=23, tm_min=12, tm_sec=0, 
                 tm_wday=6, tm_yday=109, tm_isdst=0)

So, real UTC date is 19th March 2009 23:12:00, right ?

Now I need to format my date in string, I use

>>> d.strftime('%Y-%m-%d %H:%M:%S.%f') 
'2009-04-19 21:12:00.000000'

Which doesn’t seems to take this offset into account. How to fix that ?

Asked By: snoob dogg

||

Answers:

The reason is python actually formatting your datetime object, not some “UTC at this point of time”

To show timezone in formatting, use %z or %Z.

Look for strf docs for details

Answered By: Slam

This will convert your local time to UTC and print it:

import datetime, pytz
from dateutil.tz.tz import tzoffset

loc = datetime.datetime(2009, 4, 19, 21, 12, tzinfo=tzoffset(None, -7200))

print(loc.astimezone(pytz.utc).strftime('%Y-%m-%d %H:%M:%S.%f') )

(http://pytz.sourceforge.net/)

Answered By: Patrick Artner

In addition to what @Slam has already answered:

If you want to output the UTC time without any offset, you can do

from datetime import timezone, datetime, timedelta
d = datetime(2009, 4, 19, 21, 12, tzinfo=timezone(timedelta(hours=-2)))
d.astimezone(timezone.utc).strftime('%Y-%m-%d %H:%M:%S.%f')

See datetime.astimezone in the Python docs.

Answered By: dnswlt

I couldn’t import timezone module (and hadn’t much time to know why)
so I set TZ environment variable which override the /etc/localtime information

>>> import os
>>> import datetime
>>> print  datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
2019-05-17 11:26
>>> os.environ["TZ"] = "UTC"
>>> print  datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
2019-05-17 09:26
Answered By: Emmanuel
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.