If you want to work with datetime expressions you need to import the datetime module. This gives you access to date and datetime objects and methods. For a complete overview of all the date and datetime methods: Python Dates (w3schools.com)
from datetime import date, datetime
# DateTime:
varNow = datetime.now() # 2023-03-15 12:34:22.231975
# Date:
varToday = date.today() # 2023-03-15
varYear = varToday.year # 2023
varMonth = varToday.month # 3
varquarter = (varMonth - 1) // 3 + 1Manipulating dates and adding day, months or years to a specific date you can do using the relativedelta function from the dateutil package. The standard datetime function timedelta only supports seconds, minutes, hours and days.
from datetime import timedelta
from dateutil.relativedelta import relativedelta
varYesterday = varToday - timedelta( days=1) # 14-03-2023
varPrevMonth = varToday - relativedelta( months=1) # 15-02-2023
varStartYear = date(varYear, 1, 1) # 01-01-2023
varBirthDate = date(1974, 9, 2) # 02-09-1974
# Duration:
varDuration = (varToday - varBirthDate).days # 17717Parsing dates can be very tricking because different countries use different date formats. For example in the USA dates start with the month followed by the day (03/15/2024) while in many other countries it is the other way around ( 15/03/2024 ). To make it even more complicated some countries use a dot (15.03.2024) or hyphen (15-03-2024) between de date parts. In Python you can solve this problem by specifying the format in the Method strptime().
#Localization/parsing
varDateStr = '15-03-2023' # input('Enter a date')
varDate = datetime.strptime(varDateStr, "%d-%m-%Y")\
.date() # 15-03-2023
print(varDate)Formatting dates is easy using the strftime() method.
#Format
varFormat = varDate.strftime("%B") # March
varFormat = varDate.strftime("%d-%m-%Y") # 15-03-2023
varFormat = varDate.strftime("%m/%d/%y") # 03/15/23
varFormat = varDate.strftime("%d %b %Y") # 15 Mar 2023
varFormat = varDate.strftime("%A") # Wednesday
varFormat = varNow.strftime("%H:%M" ) # 12:34
# Directive
# %a Weekday, short version Wed
# %A Weekday, full version Wednesday
# %w Weekday as a number 0-6, 0 is Sunday 3
# %d Day of month 01-31 31
# %b Month name, short version Dec
# %B Month name, full version December
# %m Month as a number 01-12 12
# %y Year, short version, without century 18
# %Y Year, full version 2018
# %H Hour 00-23 17
# %I Hour 00-12 05
# %p AM/PM PM
# %M Minute 00-59 41
# %S Second 00-59 08
# %f Microsecond 000000-999999 548513
# %z UTC offset +0100
# %Z Timezone CST
# %j Day number of year 001-366 365
# %U Week number of year, Sunday as the first day of week, 00-53 52
# %W Week number of year, Monday as the first day of week, 00-53 52
# %c Local version of date and time Mon Dec 31 17:41:00 2018
# %C Century 20
# %x Local version of date 12/31/18
# %X Local version of time 17:41:00
# %% A % character %
# %G ISO 8601 year 2018
# %u ISO 8601 weekday (1-7) 1
# %V ISO 8601 weeknumber (01-53) 01