I am trying to generate a custom time format using the Python datetime package. My original code is:

from datetime import datetime

print(datetime.now().strftime("%Y-%m-%d %H:%M:%S%z"))

Strangely, the time zone field %z is not present in the generated time string. The generated string is like:

‘2020-04-17 20:41:35’

I checked the documentation of strftime(), and the meaning of %z is:

UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if the object is naive).

Here, we need to understand what is a naive or aware time object. Simply put, a naive time object has no timezone info, thus is incomplete. On other hand, an awaretime object has timezone info and is complete. A full explanation can be found here.

By default, the time object we get from datetime.now() is a naive object, thus having no timezone info attached. To convert the time object to an aware object with our local time zone info, we can use datetime.astimezone():

aware_time = datetime.now().astimezone()
print(aware_time.strftime("%Y-%m-%d %H:%M:%S%z"))

Now, we will get the expected result:

2020-04-17 20:53:13+0800