how to get year-month-day out of datetimeobject in python

You can use the strftime method of the datetime object to get the year, month, and day individually.

Here's an example:

main.py
import datetime

# Get current date and time
now = datetime.datetime.now()

# Extract year, month and day
year = now.strftime("%Y")
month = now.strftime("%m")
day = now.strftime("%d")

print("Year:", year)
print("Month:", month)
print("Day:", day)
248 chars
14 lines

This will output:

main.py
Year: 2021
Month: 08
Day: 26
29 chars
4 lines

You can format the strftime argument according to your desired output format. In the example above, %Y represents the year with century as a decimal number, %m represents the month as a zero-padded decimal number, and %d represents the day of the month as a zero-padded decimal number.

related categories

gistlibby LogSnag