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?
There are several ways to do that.
datetime acquired by this method is in a format like:
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.
It will give you the datetime of utc, always. You can also get datetime of utc with timezone in it.
But you might want to always get the datetime of a specific timezone, not only UTC.
Thus, you can use –
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 –
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 –
Here I am using offset with timedelta of 6 hours to get the preferred datetime.
.now() is suggested in python doc over
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.