How to get the current date and time in Python

Let’s say you need the current date and time from your system to place it in a Python application. For example to place the date and time as a timestamp in a blog application so the date and time when a blog article was posted will be visible on the screen.

For that, we need to import a module called datetime which contains a class with the same name datetime.

>>> import datetime
>>> current_datetime = datetime.datetime.now() 
>>> print(current_datetime)
2017-12-11 08:18:18.685000

There are many helper functions and attributes in the datetime object that allow you to output the time, date, year, week, etc in whatever way is needed.

>>> import datetime
>>> current_datetime = datetime.datetime.now()
>>> print(current_datetime)
2017-12-11 08:38:39.574000
>>> 
>>> current_datetime.year
2017
>>> current_datetime.weekday()
0
>>> current_datetime.date()
datetime.date(2017, 12, 11)
>>> current_datetime.time()
datetime.time(8, 38, 39, 574000)
>>> current_datetime.day
11

Note:
There is another module named calendar if you need more than time and date.

Definitely, you will want to generate a string representation of the datetime object so it will be nicely displayed on the screen. For that we need to use the strftime() method.

import datetime
>>> datetime_string = datetime.datetime.now()
>>> datetime_string.strftime("%A, %Y %B %d, %I:%M %p")
'Monday, 2017 December 11, 08:51 AM'

If you want to find out what day is on a certain date in the future (or past) then you can read dates and time from a given string.

>>> birthday_2018 = datetime.datetime(year = 2018, month = 6, day = 16)
>>> birthday_2018.weekday()
5

So, in 2018 my birthday is on Saturday! (Monday = 0, Tuesday = 1, … Saturday = 5).

Leave a Reply