Python datetime Module with Examples

Python datetime Module: In this tutorial, we are going to learn about the datetime module with its classes, methods, constants with examples in Python programming language. By Hritika Rajput Last updated : June 21, 2023

What is Python datetime Module?

Date and time manipulation in Python is done using a module named datetime. It has classes that have functions to work on a date, time, timezone, and time differences. It is an inbuilt module so it does not have to be installed exclusively.

datetime module not only enables us to do the date and time calculations, but it also is helpful in output formatting via efficient attribute extraction.

Python datetime Module: Objects

datetime library involves working with date and time, which are objects in Python. Date and time objects can be categorized as "aware" or "naive".

Aware Object

An aware object contains time as well as the timezone information. An aware object can distinguish itself from other aware objects as here we know the exact time of the two objects at an instance. Classes datetime and time provide objects which may be aware or naive.

How to check if an object is naive or aware?

A datetime or time object (x) is aware only when,

  • x.tzinfo is not none
  • x.tzinfo.utcoffset(x) does not return none

Naive Object

A naive object only contains time information. It does not have timezone information. Whether a naive object is representing Coordinated Universal Time (UTC), local time, or time in some other timezone is completely dependent on the program. It can not distinguish itself from other naive objects as the timezone info is missing. Classes date provides naive objects in Python.

Python datetime Module: Constants

This module contains two constants:

  1. MINYEAR: It is the smallest valid year number for a date or datetime object. Its value is 1.
  2. MAXYEAR: It is the largest valid year number for a date or datetime object. Its value is 9999.

Python datetime Module: Classes

There are six classes available in this module which allow manipulation of date and time:

1. date Class

An object of this class represents a date(format: year, month, day) in a calendar. The calendar used for the format is currently the Gregorian calendar.

The constructor of this class requires all three parameters: year, month, and day.

Syntax:

class datetime.date(year, month, day)

The arguments should be in the following range –

MINYEAR <= year <= MAXYEAR
1 <= month <= 12
1 <= day <= number of days in the given month and year

If the value of the arguments is outside the above range, a ValueError is pointed out and if the type is not an integer, then a TypeError is raised.

Example:

from datetime import date 
 
date0 = date(2001, 10, 27) 
print("Sample date example", date0)

Output

    Sample date example 2001-10-27

date Class Methods

date class has the following class methods and attributes:

FunctionUse
today() Returns the current local date
fromtimestamp(timestamp) Return the local date corresponding to the POSIX timestamp
fromordinal(ordinal) Returns the date corresponding with Gregorian ordinal, in which 01-01-01 has ordinal 1
Range: 1 <= ordinal <= date.max.toordinal()
fromisoformat(date_string) Returns a date corresponding to a date_string given in the format YYYY-MM-DD
Available from version 3.7
fromisocalendar(year, week, day) Return a date corresponding to the ISO calendar date specified by year, week and day
Available from version 3.8

date Class Attributes

Attribute Meaning Value
date.min It is the smallest representable date. (MINYEAR,1,1)or(1,1,1)
date.max It is the largest representable date (MAXYEAR,12,31) or(9999,12,31)
date.resolution It is the smallest possible difference between non-equal date objects timedelta(days=1)

Example:

## Python program explaining the 
## use of date class methods

from datetime import date
import time

## today() function
datetoday= date.today()
print("Today's date is", datetoday) 

## fromtimestamp() function
date1 = date.fromtimestamp(time.time())
print("Date on the given timestamp is ", date1)

## fromordinal() function
ordinal0= date.fromordinal(1000)
print("Date on 1000 ordinal was", ordinal0)

## fromisoformat() function
dateiso= date.fromisoformat('2019-12-04')
print("Date in string is", dateiso)

## fromisocalendar(year,week,day) function
ii = date.fromisocalendar(2010,4,3)
print("Date on corresponding week, day and year was", ii)

Output

Today's date is 2020-04-28
Date on the given timestamp is  2020-04-28
Date on 1000 ordinal was 0003-09-27
Date in string is 2019-12-04
Date on corresponding week, day and year was 2010-01-27

date Class Instance Methods

An instance method is a method that uses an instance of a class, while the class method can be used just with the class name. Given below are the instance methods of date class:

Method Use
replace(year=self.year, month=self.month, day=self.day) Replaces the date with the arguments given in the braces, the arguments missing have the same initial value
timetuple() Return a time.struct_time.
toordinal() Return the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1
weekday() Return the day of the week as an integer, where Monday is 0 and Sunday is 6
isoweekday() Return the day of the week as an integer in ISO 8601 format, where Monday is 1 and Sunday is 7
isocalendar() Return a 3-tuple, (ISO year, ISO week number, ISO weekday)
isoformat() Return a string representing the date in ISO 8601 format, YYYY-MM-DD
__str()__ Same as isoformat
ctime() Return a string representing the date
strftime(format) Return a string representing the date, controlled by an explicit format string
__format__(format) Same as strftime

Example:

## Python program explaining the 
## use of date class instance methods

from datetime import date

## replace() function
x = date(2019, 9, 25)
x.replace(year=2010, day=15)
print("The date after replacing is", x)

## timetuple function
t = x.timetuple()
## returns a time.struct_time which is an object containing date and time details 
print ("Timetuple of the above date is", t)

## toordinal() function
d = x.toordinal()
print("The Gregorian ordinal number of the given date is", d)

## weekday() function
print("The weekday of the date",x, "is", x.weekday())

## isoweekday() function
print("The weekday of the date",x, "in ISO calendar is", x.isoweekday())

## isocalendar() function
print("A date in Gregorian calendar",x,"will be",x.isocalendar(),"in isocalendar")

## Below Functions convert date to string

## isoformat function
s=x.isoformat()
print("The date string of x in ISO 8601 format is", s)

## str function
print("The date string of x =", str(x))

## ctime() function
print("The complete string representation of date",x,"is", x.ctime())

## strftime() function
xyear =  x.strftime("%Y")
xdate_time = x.strftime("%Y/%m/%d, %H:%M:%S")
print("Date to string using format codes")
print(xyear)
print(xdate_time)

## format() function
st=format(x)
print("Date string =",st)

Output

The date after replacing is 2019-09-25
Timetuple of the above date is time.struct_time(tm_year=2019, tm_mon=9, tm_mday=25, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=268, tm_isdst=-1)
The Gregorian ordinal number of the given date is 737327
The weekday of the date 2019-09-25 is 2
The weekday of the date 2019-09-25 in ISO calendar is 3
A date in Gregorian calendar 2019-09-25 will be (2019, 39, 3) in isocalendar
The date string of x in ISO 8601 format is 2019-09-25
The date string of x = 2019-09-25
The complete string representation of date 2019-09-25 is Wed Sep 25 00:00:00 2019
Date to string using format codes
2019
2019/09/25, 00:00:00
Date string = 2019-09-25

2. time Class

An object of time class represents the local time of day, which may be adjusted via a tzinfo object. If the tzinfo is None, the time object is naive else it is aware.

Syntax:

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

Arguments are optional in the syntax, tzinfo can be None, otherwise it is an instance of tzinfo subclass. Other arguments have the following ranges:

0 <= hour < 24,
0 <= minute < 60
0 <= second < 60
0 <= microsecond < 1000000
fold in [0, 1]

The arguments should be in the given ranges otherwise a ValueError is raised.

Example:

from datetime import time
 
time0 = time(13, 24,34) 
print("Sample time object example", time0)

Output

Sample time object example 13:24:34

time Class Attributes

Time class has the following class attributes:

Attribute Meaning Value
time.min It is the smallest representable time. time(0, 0, 0, 0)
time.max It is the largest representable time. time(23, 59, 59, 999999)
time.resolution It is the smallest possible difference between non-equal time objects. timedelta(microseconds=1)

time Class Instance Methods

Most of the methods are the same as date Class. time class has following functions which use time object instances:

Methods Use
replace(hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, * fold=0) Replaces the time with the arguments given in the braces, the arguments missing have the same initial value
isoformat(timespec='auto') Return a string representing the time in ISO 8601 format
__str__() Returns a string of the given time object
strftime(format) Return a string representing the time, controlled by an explicit format string.
__format__(format) Same as strftime(format)
utcoffset() Returns offset of local time from UTC, as a timedelta object
dst() Return the daylight saving time (DST) adjustment, as a timedelta object or None if DST information isn't known
tzname() Returns the time zone name of the time object passed as a string

3. datetime Class

This class contains information on both time and date. As a date object, it assumes the Gregorian Calendar extended in both directions, and as a time object, it assumes there are 360*24 seconds every day.

Constructor Syntax:

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

Argument range and limitation similar to date and time objects.

Example:

from datetime import datetime
 
datetime0 = datetime(2020, 12, 1, 13, 2, 34) 
print("Sample datetime object example", datetime0)

datetime1 = datetime.now()
print("Date and time right now", datetime1)

Output

Sample datetime object example 2020-12-01 13:02:34
Date and time right now 2020-04-28 21:02:47.521826

datetime Class Methods

Method Use
today() Returns the current local datetime, with no timezone information
now() Returns the current local date and time
utcnow() Return the current UTC date and time, with tzinfo None
fromtimestamp(timestamp, tz=None) Returns the local date and time corresponding to the POSIX timestamp
utcfromtimestamp(timestamp) Return the UTC datetime corresponding to the POSIX timestamp, with tzinfo None
fromordinal(ordinal) Returns the datetime corresponding with the proleptic Gregorian ordinal
combine(date, time, tzinfo=self.tzinfo) Return a new datetime object whose date components are equal to the given date object’s and time components are equal to the given time object’s
fromisoformat(date_string) Return a datetime corresponding to a date_string
fromisocalendar(year, week, day) Returns a datetime corresponding to the ISO calendar date specified by year, week and day.
strptime(date_string, format) Return a datetime for the given date_string, parsed according to the given format.

datetime Class Attributes

Attributes Use Value
datetime.min It is the earliest representable datetime datetime(MINYEAR, 1, 1, tzinfo=None)
datetime.max It is the last representable datetime datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=None)
datetime.resolution It is the smallest possible difference between non-equal datetime objects timedelta(microseconds=1)

Example:

## Python program explaining the 
## use of datetime class methods

from datetime import datetime
import time

## today() function
datetoday = datetime.today()
print("Today's date:", datetoday)

## now() function
datetodaywithtime = datetime.now()
print("Today's date with time:", datetodaywithtime)

## utcnow() function
datetimeutc = datetime.utcnow()
print("Current corresponding UTC time and date", datetimeutc)

## fromtimestamp(timestamp, tz=None) function
x1 = datetime.fromtimestamp(time.time())
print(x1)

## utcfromtimestamp(timestamp)
x2 = datetime.utcfromtimestamp(time.time())
print(x2)

##fromordinal(ordinal)
print("Date on ordinal 100000", datetime.fromordinal(100000))

##strptime(date_string, format)
print("Date string:", datetime.strptime("04 May, 2020" ,"%d %B, %Y"))

##fromisoformat(date_string)
st =  datetime.fromisoformat(str(datetoday))
print("Date string of the object:", st)


##fromisocalendar(year, week, day)
print("Date on year 2019, 7th week and 4th day in isocalendar was:", datetime.fromisocalendar(2019, 7, 4))

Output

Today's date: 2020-04-28 21:07:46.878993
Today's date with time: 2020-04-28 21:07:46.879494
Current corresponding UTC time and date 2020-04-28 21:07:46.879529
2020-04-28 21:07:46.879543
2020-04-28 21:07:46.879556
Date on ordinal 100000 0274-10-16 00:00:00
Date string: 2020-05-04 00:00:00
Date string of the object: 2020-04-28 21:07:46.878993
Date on year 2019, 7th week and 4th day in isocalendar was: 2019-02-14 00:00:00

datetime Class Instance Attributes

Attributes Value
datetime.year MINYEAR <= year <-= MAXYEAR
datetime.month 1 <= month <= 12
datetime.day 1 <= day <= Number of days in that month of that year
datetime.hour range(24)
datetime.minute range(60)
datetime.second range(60)
datetime.microsecond range(1000000)
datetime.tzinfo Object passed as tzinfo argument in object declaration, None if none was passed
datetime.fold In [0,1]
Available from version 3.6

datetime Class Instance Methods

Instance methods include many methods same as in date and time class:

Method Use
date() Returns date object with same year, month and day
time() Return time object with same hour, minute, second, microsecond and fold. tzinfo is None.
timetz() Return times object with same hour, minute, second, microsecond, fold, and tzinfo attributes.
replace(year=self.year, month=self.month, day=self.day, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, * fold=0) Replaces the datetime with the arguments given in the braces, the arguments missing have the same initial value
astimezone(tz=None) Return a datetime object with new tzinfo attribute tz
utcoffset(dt) Returns offset of local time from UTC, as a timedelta object
dst() Return the daylight saving time (DST) adjustment, as a timedelta object or None if DST information isn’t known
tzname() Returns the time zone name of the datetime object passed as a string
timetuple() Return a time.struct_time such as returned by date.timetuple()
utctimetuple() If datetime instance d is naive, it is same as timetuple() except that tm_isdst is forced to 0 regardless of what d.dst() returns.
toordinal() Returns the proleptic Gregorian ordinal of the given date
timestamp() Returns POSIX timestamp corresponding to the given date
weekday() Returns the day of the week as an integer, where Monday is 0 and Sunday is 6
isoweekday() Returns the day of the week as an integer, where Monday is 1 and Sunday is 7
isocalendar() Returns a 3-tuple, (ISO year, ISO week number, ISO weekday)
isoformat() Return a string containing date and time in ISO 8601 format
__str__() String representation of the given datetime
ctime() Same as str
strftime() Returns a string representing the date and time, controlled by an explicit format string.
__format__() Same as strftime()

4. timedelta Class

An object of timedelta class represents the value of the difference between two dates or times.

Syntax:

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

timedelta Class Attributes

Attribute Meaning Value
timedelta.min It is the most negative timedelta object timedelta(-999999999)
timedelta.max It is the most positive timedelta object timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999)
timedelta.resolution It is the smallest possible difference between non-equal timedelta objects timedelta(microseconds=1)

timedelta Class Instance Attributes

Attributes Range
days Between -999999999 and 999999999 inclusive
second Between 0 and 86399 inclusive
millisecond Between 0 and 999999 inclusive

timedelta Class Instance Method

timedelta class has one instance method: total_seconds() which returns the total number of seconds covered in the given duration.

Example:

## Python program to illustrate 
## the use of timedelta class
from datetime import datetime, timedelta  
    
presentdate = datetime.now()  
print ("Present date:", str(presentdate))  
    
## Date and time after 4 years
date1 = presentdate + timedelta(days = (4*365))  
print ("Date after 4 years from now", str(date1))  
    
# Date and time after 4 years 2 months 3 hours from now  
date2 = presentdate + timedelta(days = (4*365+2*30), hours=3)   
print ("Date after 4 years 2 months 3 hours from now", str(date2))

## total_seconds function
total = timedelta(minutes = 2*15).total_seconds()
print("Total seconds in 30 minutes:", total)

Output

Present date: 2020-04-28 21:19:25.932396
Date after 4 years from now 2024-04-27 21:19:25.932396
Date after 4 years 2 months 3 hours from now 2024-06-27 00:19:25.932396
Total seconds in 30 minutes: 1800.0

5. tzinfo Class

tzinfo is an abstract base class, ie, it cannot be instantiated directly. A concrete subclass has to derive it and implement the methods provided by this abstract class.

We had learnt about the aware objects that when the instance of the tzinfo class(not None) is passed to the constructors of the datetime and time objects, they become aware objects. It helps in the conversion of local time to UTC or account for daylight saving time.

tzinfo Class Methods

Method Use
utcoffset(dt) Returns offset of local time from UTC, as a timedelta object
dst(dt) Returns the daylight saving time (DST) adjustment, as a timedelta object or None if DST information isn’t known
tzname(dt) Returns the time zone name of the datetime object passed as a string
fromutc(dt) Returns the equivalent local time corresponding to the date and time of the object in UTC

Example:

from datetime import datetime
import pytz

naive= datetime.now()
## Tzinfo is missing from the time object which is naive 
print(naive)
print(naive.tzinfo)
timezone = pytz.timezone("Europe/Berlin")
aware = timezone.localize(naive)

## After adding the timezone info, the object it becomes aware
print(aware)
print(aware.tzinfo)

Output

2020-04-29 14:32:13.640369
None
2020-04-29 14:32:13.640369+02:00
Europe/Berlin

6. timezone Class

The timezone class is a subclass of tzinfo. Every instance of this class represents a timezone defined by a fixed offset from UTC.

Syntax:

class datetime.timezone(offset, name=None)

The offset argument must be specified as a timedelta object representing the difference between the local time and UTC.

Range of the offset:

-timedelta(hours=24) <= offset <= timedelta(hours=24)

If the offset is east of UTC, then it is considered positive and if it is west of UTC, it is negative. Since there are 24 hours in a day, -timedelta(24) and timedelta(24) are the largest values possible.

timezone Class Methods

Since it is a subclass of tzinfo, the methods of this class are the same as tzinfo.

Reference: datetime — Basic date and time types

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.