DEV Community

Cover image for Date and Time in Python
Daniel Nogueira
Daniel Nogueira

Posted on

Date and Time in Python

We can get data and time information in Python using the datetime module. Let's import it:

import datetime
Enter fullscreen mode Exit fullscreen mode

Date

In the datetime module we can use the date class, which has today() to load the current day's data:

date = datetime.date.today()
print(date)
Enter fullscreen mode Exit fullscreen mode

Result example:

2023-01-04
Enter fullscreen mode Exit fullscreen mode

We can also get each date information separately:

day = datetime.date.today().day
month = datetime.date.today().month
year = datetime.date.today().year

print(day)
print(month)
print(year)
Enter fullscreen mode Exit fullscreen mode

Result example:

4
1
2023
Enter fullscreen mode Exit fullscreen mode

Time

To get the time, we'll use the datetime class and its now() method:

now = datetime.datetime.now()
print(now)
Enter fullscreen mode Exit fullscreen mode

Result example:

2023-01-04 14:28:19.041413
Enter fullscreen mode Exit fullscreen mode

Note that the time schedule is organized into:

hour:minute:second.microsecond

Time formatting

We can change the way the time is being displayed through the strftime() method. By default, we have %d for day, %m for month, %y for year, %H for hour, %M for minute and %S for seconds. Let's use new variables to save these formatted values:

format1 = now.strftime('%d/%m/%y')
print(format1)

format2 = now.strftime('%d.%m.%Y %H:%M:%S')
print(format2)
Enter fullscreen mode Exit fullscreen mode

Result example:

01/04/23
04.01.2023 14:28:19
Enter fullscreen mode Exit fullscreen mode

Note that using %Y, we have the year displayed with 4 characters.

Top comments (0)