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
πŸ† Live Soccer TV: udanielnogueira/date and time in python ebb - Pertandingan Hari Ini πŸ† Live Soccer TV: udanielnogueira/date and time in python ebb - Pertandingan Hari Ini

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)
πŸ† Live Soccer TV: udanielnogueira/date and time in python ebb - Pertandingan Hari Ini πŸ† Live Soccer TV: udanielnogueira/date and time in python ebb - Pertandingan Hari Ini

Result example:

2023-01-04
πŸ† Live Soccer TV: udanielnogueira/date and time in python ebb - Pertandingan Hari Ini πŸ† Live Soccer TV: udanielnogueira/date and time in python ebb - Pertandingan Hari Ini

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)
πŸ† Live Soccer TV: udanielnogueira/date and time in python ebb - Pertandingan Hari Ini πŸ† Live Soccer TV: udanielnogueira/date and time in python ebb - Pertandingan Hari Ini

Result example:

4
1
2023
πŸ† Live Soccer TV: udanielnogueira/date and time in python ebb - Pertandingan Hari Ini πŸ† Live Soccer TV: udanielnogueira/date and time in python ebb - Pertandingan Hari Ini

Time

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

now = datetime.datetime.now()
print(now)
πŸ† Live Soccer TV: udanielnogueira/date and time in python ebb - Pertandingan Hari Ini πŸ† Live Soccer TV: udanielnogueira/date and time in python ebb - Pertandingan Hari Ini

Result example:

2023-01-04 14:28:19.041413
πŸ† Live Soccer TV: udanielnogueira/date and time in python ebb - Pertandingan Hari Ini πŸ† Live Soccer TV: udanielnogueira/date and time in python ebb - Pertandingan Hari Ini

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)
πŸ† Live Soccer TV: udanielnogueira/date and time in python ebb - Pertandingan Hari Ini πŸ† Live Soccer TV: udanielnogueira/date and time in python ebb - Pertandingan Hari Ini

Result example:

01/04/23
04.01.2023 14:28:19
πŸ† Live Soccer TV: udanielnogueira/date and time in python ebb - Pertandingan Hari Ini πŸ† Live Soccer TV: udanielnogueira/date and time in python ebb - Pertandingan Hari Ini

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

Top comments (0)