Pythons datetime of a timezone

brown hourglass on brown wooden table
Photo by Mike on Pexels.com

In python, we can use datetime module from standard library for manipulating dates and times. From the documentation, we can say, date and time objects may be categorized as “aware” or “naive” depending on whether or not they include timezone information. How can we get a datetime?

brown hourglass on brown wooden table
Photo by Mike on Pexels.com

There are several ways to do that.

>>> datetime.datetime.now()

datetime acquired by this method is in a format like:

'2021-03-30 14:53:47.118846'

It is naive, doesn’t have timezone information. What this now() does is taking local systems timezone to give the datetime. So, it does depend on the system it will be running on.

If somehow you forgot to check the timezone of the system, then it can cause a problem. Depending on the system is not always suggested. Obviously it depends on your choice.

By the way, you can also get defined datetime of a specific timezone.

>>> datetime.datetime.utcnow()

It will give you the datetime of utc, always. You can also get datetime of utc with timezone in it.

>>> datetime.datetime.now(datetime.timezone.utc)
'2021-03-30 14:44:37.652991+00:00'

But you might want to always get the datetime of a specific timezone, not only UTC.

Thus, you can use –

>>> datetime.datetime.now(tz=??)

Here you need to pass tzinfo, abstract base class for time zone info classes. For ease of use, I think you might want to get the timezone by mentioning the City. On that case, you need another module from pypi which is not built in, called pytz.

After importing pytz, you can then get datetime –

>>> datetime.datetime.now(tz=pytz.timezone("Asia/Dhaka"))
'2021-03-30 21:00:16.877009+06:00'

This is good, but problem is you are depending on another library for the timezone. You can bypass this by using datetime itself to get the datetime with timezone in it of a preferred timezone. But you need to know the difference from UTC. As of my case, Asia/Dhaka is 6 hours ahead of UTC. So it is UTC+6. What I can do to get the similar datetime –

>>> datetime.datetime.now(tz=datetime.timezone(offset=datetime.timedelta(hours=6)))

Here I am using offset with timedelta of 6 hours to get the preferred datetime.

'2021-03-30 21:04:35.772636+06:00'

Using .now() is suggested in python doc over .utcnow().

So, if I summarize, for production, you always should check which timezone your code is using. Otherwise, you will fall into a chaos with data.

By the way, datetime is a very powerful module. I will post some unique queries which can be handled by datetime and it’s functions.