If you have been Programming -at least- for a while, I am pretty sure you came across with use-cases where you’d have to work with date(time)s and timestamps.
When working with such constructs, it is pretty important to ensure that you make use of timezone-aware objects. In production environments, it is quite common to see many different services across the globe to be connected to each other in order to achieve a certain task. This means that we – as programmers – need to ensure that we avoid timezone-naive constructs that could potentially introduce unwanted bugs.
In the next few sections we will go through a few different approaches you can follow in order to programmatically compute the current time in Python.
More specifically, we will demonstrate how to infer current date and/or time and timestamp using datetime
and time
modules. Additionally, we will discuss how to process datetime as strings as well as how to take into account timezones.
How to compute the current time in Python
Now in order to programmatically infer the current datetime in Python, we can use datetime
module as outlined below:
>>> from datetime import datetime
>>>
>>> now = datetime.now()
>>> now
datetime.datetime(2022, 9, 30, 16, 34, 24, 88687)
The above expression will return an object of type datetime.datetime
. If you’d like to print out the datetime in a more intuitive and human-readable format, all you need to do is either cast it to str
(e.g. str(now)
) or call the strftime()
to specify the exact string format you’d want the new string object to have.
For example, let’s assume we want to keep only the date part of the datetime whilst discarding the time information. The following should do the trick:
>>> now_dt = now.strftime('%d-%m-%Y')
>>> now_dt
'30-09-2022'
Similarly, if you’d like to keep only the time part of the datetime object, you could use the time()
method:
>>> from datetime import datetime
>>> now_time = datetime.now().time()
>>> now_time
datetime.time(16, 43, 12, 192517)
Again, we can format the above datetime object in such a way that we convert it into a string. If we wanted to discard the millisecords part and just keep the hour, minutes and seconds, then the following expression would do the trick for us:
>>> now_time.strftime('%H:%M:%S')
'16:43:12'
Another useful module that can help us deal with times is the built-in time
. The ctime
method will return a string of the current time, based on the datetime configuration of your operating system and your host machine.
>>> import time
>>> time.ctime()
'Fri Sep 30 16:48:22 2022'
Introducing timezone-aware datetime objects
Now the problem with what we showed in the previous section is that the datetime objects we created are timezone-naive. For example, I am based in London – this means that if myself and one other person based in the US or India runs the same commands we demonstrated earlier at the same point in time, we will all end up with different results since all of the expressions above will compute the current time based on the timezone of the host machine (that obviously varies from location to location).
Universal Coordinated Time (UTC) is a global standard that has also been adopted in the community of programmers. UTC is (nearly) equivalent to GMT and it does not change for Daylight Savings Time etc. It is quite common to communicate datetime-related requirements in UTC, since it’s the universal timezone and its adoption can help people communicate easier when it comes to datetimes and scheduling. Other common programming constructs such as timestamps/unix epoch time also use UTC in order to be computed.
Going back to our previous examples, let’s try to infer the timezone of the constructed datetime object. Once again, note that I am based in London and by the time of writing this article we were in British Summer Time (BST):
>>> from datetime import datetime
>>> now = datetime.now()
>>> tz = now.astimezone().tzinfo
>>> tz
datetime.timezone(datetime.timedelta(seconds=3600), 'BST')
Now if you are on a different timezone and run the above commands, you will get different values for both now
and tz
– and this is exactly where the problem lies.
Instead, we could compute the current datetime in UTC timezone such that all of us we’ll end up with the same calculations. Given that I am based in London (currently in BST), we expect that the current UTC datetime will be one hour behind my local BST timezone:
>>> from datetime import datetime
>>> now = datetime.utcnow()
>>> now
datetime.datetime(2022, 9, 30, 16, 22, 22, 386588)
Note that it is also possible to change the timezone information of a datetime object by calling the replace()
method and providing one of the timezone options available in datetime.timezone
module.
For example, let’s create a datetime object of the current datetime (in BST):
>>> from datetime import datetime, timezone
>>> now = datetime.now()
>>> now
datetime.datetime(2022, 9, 30, 17, 26, 15, 891393)
>>> now_utc = now.replace(tzinfo=timezone.utc)
datetime.datetime(2022, 9, 30, 17, 26, 15, 891393, tzinfo=datetime.timezone.utc)
Final Thoughts
In today’s article we demonstrated a few different ways for computing datetimes and timestamps in Python. This can be achieved with the use of one of the two built-in modules, namely datetime
and time
.
Additionally, we discussed about the importance of working with timezone-aware constructs. Modern systems running in production usually involve many different services hosted across the whole globe.
This means that services hosted on different countries will be on a different timezone and therefore we somehow need to deal with this irregularity in a consistent and accurate way.
This is the reason why we usually want to work with timezone-aware objects. Furthermore, it is quite common in the context of programming to stick to UTC timezone and unix timestamps.
We will discuss more about UTC and Unix Epoch Time in one of my upcoming articles, so make sure to keep an eye 🙂
Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium.
Related articles you may also like