Skip to main content
  1. Posts/

Get Current Time with Time Zone Info in Python

·195 words·1 min·
Python
Table of Contents

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

References
#

Related

Retry for Google Cloud Client
·197 words·1 min
Python GCP
Make Python logging Work in GCP
·570 words·3 mins
Python Logging GCP
Speed up document indexing in Elasticsearch via bulk indexing
·355 words·2 mins
Python Elasticsearch