break up a date into day, month, and year in python

You can use the datetime module in Python to break up a date into day, month, and year. First, you need to create a datetime object using the date string. Then, you can get the individual day, month, and year components using the day, month, and year attributes of the datetime object, respectively. Here is an example:

main.py
from datetime import datetime

# define the date string
date_string = '2022-11-30'

# parse the date string into a datetime object
dt = datetime.strptime(date_string, '%Y-%m-%d')

# get the day, month, and year components
day = dt.day
month = dt.month
year = dt.year

print('Day:', day)
print('Month:', month)
print('Year:', year)
331 chars
17 lines

Output:

main.py
Day: 30
Month: 11
Year: 2022
29 chars
4 lines

In the above example, we first define the date string '2022-11-30'. Then, we use the strptime method of the datetime class to parse the date string into a datetime object dt, using the format string '%Y-%m-%d' which specifies the year (%Y), month (%m), and day (%d) components of the string. Finally, we extract the day, month, and year components of dt using the day, month, and year attributes, respectively, and print them to the console.

gistlibby LogSnag