Table of Contents
How to use date, datetime and time objects?
from datetime import date from datetime import time from datetime import datetime #Get current date today = date.today() print(today) #get current day print(today.day) #Get current month print(today.month) #Get current year print(today.year)
Formatting time output
strftime() method
The datetime object has strftime() method for formatting date objects into readable strings.
Strftime() takes one parameter to specify the format of the returned string:
#Get current date and time now = datetime.now() print(now.strftime("The current year is: %Y")) print(now.strftime("The current time is: %a, %d %m %Y"))
How to get locale specific date/time?
#Get locale date and time print(now.strftime("Locale date and time is: %c")) print(now.strftime("Locale date is: %x")) print(now.strftime("Locale time is: %X"))
Time formating
%I / %H – 12 / 24 Hour
%M – Minute
%S – Second
%p – locale’s AM/PM
#Get current time print(now.strftime("Current time is: %I %M %S %p"))
Using timedelta objects
Python timedelta object is used to perform mathematical operations with dates and times.
from datetime import timedelta print(timedelta(days=365, hours=10, minutes=15)) #365 days, 10:15:00 #Get current date and time now = datetime.now() #Get today's date one year from now print("One year from now: " + str(now + timedelta(days=365)))
Working with calendars
Import the calendar module
import calendar
How to create a plain text calendar?
import calendar #Create a plain text calendar c = calendar.TextCalendar(calendar.MONDAY) st = c.formatmonth(2020,1,0,0) print(st)
How to create an HTML formatted calendar?
import calendar #Create an HTML formatted calendar h = calendar.HTMLCalendar(calendar.MONDAY) st = h.formatmonth(2020,1) print(st)
How to loop over the days of a month?
#Loop over the days of a month c = calendar.TextCalendar(calendar.MONDAY) for i in c.itermonthdays(2020,1): print(i)
The zeros at the start and the end indicate that there are days in that week that belong to another month.
Exercises and examples with date, datetime, and time objects
Print the number of days from today until 30 October?
today=date.today() hday=date(today.year,10,30) diff=(hday-today).days if diff>0: print("There are %d days left" % diff) else: print("There are %d days left" % (diff+365))
Hello there!
I hope you find this post useful!I'm Mihai, a programmer and online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.
If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!