How to get today's year, month, day in Python

We can get today's date by importing datetime.

import datetime

today = datetime.date.today()

print(today)  # 2020-09-19
print(type(today))  # <class 'datetime.date'>

The function today returns a datetime.date object and the value as string is like 2020-09-19. This is not a string so we can't split.

import datetime

today = datetime.date.today()

print(today)  # 2020-09-19
print(type(today))  # <class 'datetime.date'>

a = today.split('-')
print(a)
# AttributeError: 'datetime.date' object has no attribute 'split'

How to get the current year, month and day

So how can we get the current year?

import datetime

today = datetime.date.today()

print(today)  # 2020-09-19
print(type(today))  # <class 'datetime.date'>

year = today.year
month = today.month
day = today.day

print(year)  # 2020
print(month)  # 9
print(day)  # 19

today has some read-only attributues such as year, month, day.

Python Date & Time

Python Tutorial