Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 999
snoob dogg Avatar asked Feb 10 '18 19:02

snoob dogg


People also ask

How do you make a datetime object timezone aware?

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.

How do I add time zones to Strftime?

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

Does Python datetime have timezone?

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.


2 Answers

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.

like image 120
dnswlt Avatar answered Sep 20 '22 19:09

dnswlt


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

like image 26
Slam Avatar answered Sep 19 '22 19:09

Slam