Sunday, October 2, 2022
HomeData ScienceHow To Get The Present Time In Python

How To Get The Present Time In Python


Computing the present date and time programmatically with Python

Photograph by Djim Loic on Unsplash

You probably have been programming -at least- for some time, I’m fairly certain you got here throughout with use-cases the place you’d should work with date(time)s and timestamps.

When working with such constructs, it’s fairly essential to make sure that you make use of timezone-aware objects. In manufacturing environments, it’s fairly widespread to see many various companies throughout the globe to be related to one another with a view to obtain a sure activity. Which means that we — as programmers — want to make sure that we keep away from timezone-naive constructs that might probably introduce undesirable bugs.

Within the subsequent few sections we are going to undergo a number of completely different approaches you may observe with a view to programmatically compute the present time in Python.

Extra particularly, we are going to reveal infer present date and/or time and timestamp utilizing datetime and time modules. Moreover, we are going to talk about course of datetime as strings in addition to keep in mind timezones.

Easy methods to compute the present time in Python

Now with a view to programmatically infer the present datetime in Python, we will use datetime module as outlined beneath:

>>> 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 sort datetime.datetime. For those who’d wish to print out the datetime in a extra intuitive and human-readable format, all you have to do is both solid it to str (e.g. str(now)) or name the strftime() to specify the precise string format you’d need the brand new string object to have.

For instance, let’s assume we need to preserve solely the date a part of the datetime while discarding the time data. The next ought to do the trick:

>>> now_dt = now.strftime('%d-%m-%Y')
>>> now_dt
'30-09-2022'

Equally, for those who’d wish to preserve solely the time a part of the datetime object, you would use the time() methodology:

>>> from datetime import datetime
>>> now_time = datetime.now().time()
>>> now_time
datetime.time(16, 43, 12, 192517)

Once more, we will format the above datetime object in such a approach that we convert it right into a string. If we wished to discard the millisecords half and simply preserve the hour, minutes and seconds, then the next expression would do the trick for us:

>>> now_time.strftime('%H:%M:%S')
'16:43:12'

One other helpful module that may assist us take care of instances is the built-in time. The ctime methodology will return a string of the present time, primarily based on the datetime configuration of your working system and your host machine.

>>> import time
>>> time.ctime()
'Fri Sep 30 16:48:22 2022'

Introducing timezone-aware datetime objects

Now the issue with what we confirmed within the earlier part is that the datetime objects we created are timezone-naive. For instance, I’m primarily based in London — which means if myself and one different particular person primarily based within the US or India runs the identical instructions we demonstrated earlier on the similar time limit, we are going to all find yourself with completely different outcomes since all the expressions above will compute the present time primarily based on the timezone of the host machine (that clearly varies from location to location).

Common Coordinated Time (UTC) is a world normal that has additionally been adopted locally of programmers. UTC is (practically) equal to GMT and it doesn’t change for Daylight Financial savings Time and so forth. It’s fairly widespread to speak datetime-related necessities in UTC, because it’s the common timezone and its adoption may also help individuals talk simpler on the subject of datetimes and scheduling. Different widespread programming constructs similar to timestamps/unix epoch time additionally use UTC with a view to be computed.

Going again to our earlier examples, let’s attempt to infer the timezone of the constructed datetime object. As soon as once more, word that I’m primarily based in London and by the point of writing this text we have been in British Summer time Time (BST):

>>> from datetime import datetime
>>> now = datetime.now()
>>> tz = now.astimezone().tzinfo
>>> tz
datetime.timezone(datetime.timedelta(seconds=3600), 'BST')

Now in case you are on a special timezone and run the above instructions, you’ll get completely different values for each now and tz — and that is precisely the place the issue lies.

As a substitute, we may compute the present datetime in UTC timezone such that each one of us we’ll find yourself with the identical calculations. Provided that I’m primarily based in London (presently in BST), we anticipate that the present UTC datetime can be one hour behind my native BST timezone:

>>> from datetime import datetime
>>> now = datetime.utcnow()
>>> now
datetime.datetime(2022, 9, 30, 16, 22, 22, 386588)

Word that additionally it is potential to alter the timezone data of a datetime object by calling the change() methodology and offering one of many timezone choices out there in datetime.timezone module.

For instance, let’s create a datetime object of the present datetime (in BST):

>>> from datetime import datetime, timezone
>>> now = datetime.now()
>>> now
datetime.datetime(2022, 9, 30, 17, 26, 15, 891393)
>>> now_utc = now.change(tzinfo=timezone.utc)
datetime.datetime(2022, 9, 30, 17, 26, 15, 891393, tzinfo=datetime.timezone.utc)

Last Ideas

In immediately’s article we demonstrated a number of other ways for computing datetimes and timestamps in Python. This may be achieved with the usage of one of many two built-in modules, specifically datetime and time.

Moreover, we mentioned concerning the significance of working with timezone-aware constructs. Trendy techniques operating in manufacturing normally contain many various companies hosted throughout the entire globe.

Which means that companies hosted on completely different international locations can be on a special timezone and subsequently we by some means must take care of this irregularity in a constant and correct approach.

That is the rationale why we normally need to work with timezone-aware objects. Moreover, it’s fairly widespread within the context of programming to stay to UTC timezone and unix timestamps.

We’ll talk about extra about UTC and Unix Epoch Time in one in every of my upcoming articles, so be certain that to maintain an eye fixed 🙂

Develop into a member and skim each story on Medium. Your membership charge immediately helps me and different writers you learn. You’ll additionally get full entry to each story on Medium.

Associated articles you might also like

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments