47

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 ?

snoob dogg
  • 2,491
  • 3
  • 31
  • 54

4 Answers4

45

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.

rjdkolb
  • 10,377
  • 11
  • 69
  • 89
dnswlt
  • 2,925
  • 19
  • 15
16

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

Slam
  • 8,112
  • 1
  • 36
  • 44
  • 2
    Since by default `%z` seems to give the offset without colon (`:`), this might also be useful: https://gist.github.com/mattstibbs/a283f55a124d2de1b1d732daaac1f7f8 – Luiz Tauffer Sep 01 '21 at 13:20
  • 1
    Yes, python still does not provide support for `%:z` formatting, but just to warn you on your gist: there's support for sub-minute TZs in python, so your code may break on exotic data – Slam Sep 01 '21 at 20:54
2

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/)

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
1

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
Emmanuel
  • 177
  • 3