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 ?
Timezone aware object using pytz You can also use the pytz module to create timezone-aware objects. For this, we will store the current date and time in a new variable using the datetime. now() function of datetime module and then we will add the timezone using timezone function of pytz module.
To show timezone in formatting, use %z or %Z .
One of the modules that helps you work with date and time in Python is datetime . With the datetime module, you can get the current date and time, or the current date and time in a particular time zone.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With