We can get data and time information in Python using the datetime module. Let's import it:
import datetime
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)
Result example:
2023-01-04
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)
Result example:
4
1
2023
Time
To get the time, we'll use the datetime class and its now() method:
now = datetime.datetime.now()
print(now)
Result example:
2023-01-04 14:28:19.041413
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)
Result example:
01/04/23
04.01.2023 14:28:19
Note that using %Y, we have the year displayed with 4 characters.
              
    
Top comments (0)