Python Datetime Module: All You Need to Know - CNDRO.LLC
3092
post-template-default,single,single-post,postid-3092,single-format-standard,wp-custom-logo,theme-bridge,bridge-core-2.9.4,woocommerce-no-js,tribe-no-js,ehf-template-bridge,ehf-stylesheet-bridge-child,qode-page-transition-enabled,ajax_fade,page_not_loaded,,qode-title-hidden,qode_grid_1300,footer_responsive_adv,hide_top_bar_on_mobile_header,columns-4,qode-child-theme-ver-1.0.0,qode-theme-ver-27.8,qode-theme-bridge,qode_header_in_grid,wpb-js-composer js-comp-ver-6.7.0,vc_responsive,elementor-default,elementor-kit-2634

Python Datetime Module: All You Need to Know

Python datetime is a module to work with dates in python which consists of four main classes which are: date, timedelta, time, and datetimes. We’ll implement how each of these objects can be used in our code.

The Date Class

The object represents a date which is an attribute of the year, month and day in an idealized calendar, the current Gregorian calendar indefinitely extended in both directions whereby January 1 of year 1 is called day number 1, January 2 of year 1 is called day number 2, and so on.

The constructor of this class is represented as class datetime.date(year, month, day).

For instance, we can have;

from datetime import date
 
# date object of today's date
today = date.today()
 
print("Current year:", today.year)
print("Current month:", today.month)
print("Current day:", today.day)

 

The TimeDelta Class

Python timedelta class is used for calculating differences in dates and times. This timedelta supports mathematical operations like additions, subtractions, multiplication, division etc.

The constructor class for TimeDelta;

class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

Calculating difference between two date and times

# Timedelta function demonstration
from datetime import datetime, timedelta

# Using current time
current_time= datetime.now()
# printing initial_date
print("date_now", str(current_time))

# the other datetime
result_date = current_time + \
timedelta(days=5)

# printing new result_date
print("new_result_time", str(result_date))

# printing calculated past_dates
print('Time difference:', str(result_date -current_time))

 

Different Operations supported by TimeDelta class

Operator

Description

Addition (+)

Adds and returns two timedelta objects

Subtraction (-)

Subtracts and returns two timedelta objects

Multiplication (*)

Multiplies timedelta object with float or int

Division (/)

Divides the timedelta object with float or int

Floor division (//)

Divides the timedelta object with float or int and return the int

Modulo (%)

Divides two timedelta object and returns the remainder

+(timedelta)

Returns the same timedelta object

-(timedelta)

Returns the resultant of -1*timedelta

 

The Time Class

The time class of python datetime module represents a time quantity. The time class usually contain a tzinfo representing the timezone for which the time is specified. We must note that the date class doesn’t possess attributes related to time, also the time class doesn’t have date information, it’s only the dateclass that has both attributes pertaining to date and time.

The constructor class for Time is;

class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

An example of how we can represent time by calling the time constructor is shown below.

Representation of Time and obtaining hours, minutes, seconds, and microseconds

from datetime import time
 
# calling the constructor
my_time = time(13, 24, 56)
 
print("Entered time", my_time)
# call the constructor with just one argument
my_time = time(minute=12)
print("result with one argument", my_time)
# Calling constructor with no argument
my_time = time()
print("Time with no argument", my_time)
 
Time = time(20, 25, 50)
 
print("hour =", Time.hour)
print("minute =", Time.minute)
print("second =", Time.second)
print("microsecond =", Time.microsecond)

 

The DateTime Class

The DateTime class contains information on both date and time. The constructor class for the datetime class is ;

class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0) 

Note: The year, month and day are very mandatory. The tzinfo can be set as None while the other attributes must be an integer.

Representation of the Datetime class, get year, month, hour, minute, and timestamp

# A program to demonstrate datetime object
 
from datetime import datetime
# call the constructor
one = datetime(2001, 10, 12)
print(one)
 
# call the constructor with time parameters as well
two = datetime(2001, 12, 10, 12, 12, 12, 212390)
print(two)
#call the year, month, hour, minute, timestamp
a = datetime(2001, 12, 10, 12, 12, 12)
 
print("year =", a.year)
print("month =", a.month)
print("hour =", a.hour)
print("minute =", a.minute)
print("timestamp =", a.timestamp())

 

We have the following Date class methods which we can use, you can check the documentation to get more.

Function Name

Description

now()

Returns current local date and time with tz parameter

replace()

Changes the specific attributes of the DateTime object

strftime()

Returns a string representation of the DateTime object with the given format

strptime()

Returns a DateTime object corresponding to the date string

time()

Return the Time class object

timetuple()

Returns an object of type time.struct_time

timetz()

Return the Time class object

today()

Return local DateTime with tzinfo as None

 

Converting DateTime to Strings

We also need to convert our datetime to strings which can be for different reason. To convert datetime to strings, we will use the datetime.strftime and datetime.isoformat methods.

Using ISO Format

>>dt = datetime.now()
>>print([dt.isoformat()])
['2022-03-16T16:23:21.505760']

Using the String Format time Method (.strftime format)

>>> print(dt.strftime('Today is %Y, %B %d'))
Today is 2022, March 16
>>> print(dt.strftime('Date: %d/%m/%Y Time: %H:%M:%S'))
Date: 16/03/2022 Time: 16:28:54

These dates are usually in the form YYYY-MM-DD T HH:MM:SS.Microseconds

The following are time format codes in Python which we can explore:

%Y: the year in 4 digits

%y: the year in 2 digits

%m: month in 2 digits

%B: full name of the month

%w: week number from 0 to 6

%A: full name of the weekday

%a: first three letters for the weekday

%W: returns the week number of the year

%d: day of the month

%j: day of the year

%H: hour

%M: minute

No Comments

Post A Comment