How to work with Python date, datetime, and time objects

working with date in python

How to use date, datetime and time objects?

from datetime import date
from datetime import time
from datetime import datetime

#Get current date
today =

#get current day

#Get current month

#Get current 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 =
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 =

#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)

How to create an HTML formatted calendar?

import calendar

#Create an HTML formatted calendar
h = calendar.HTMLCalendar(calendar.MONDAY)
st = h.formatmonth(2020,1)

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):

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?
if diff>0:
  print("There are %d days left" % diff)
  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!

subscribe youtube

Leave a Reply

Your email address will not be published. Required fields are marked *