The Wayback Machine - https://web.archive.org/web/20240710065348/https://www.geeksforgeeks.org/python-datetime-datetime-class/
Open In App

Python DateTime – DateTime Class

Last Updated : 27 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

DateTime class of the DateTime module as the name suggests contains information on both dates as well as time. Like a date object, DateTime assumes the current Gregorian calendar extended in both directions; like a time object, DateTime assumes there are exactly 3600*24 seconds in every day. But unlike the date class, the objects of the DateTime class are potentially aware objects i.e. it contains information regarding time zone as well.

Syntax of Python DateTime

The syntax of the Python DateTime class is as follows:

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

The year, month, and day arguments are mandatory. The tzinfo can be None, and the rest all the attributes must be an integer in the following range:

  • MINYEAR(1) <= year <= MAXYEAR(9999)
  • 1 <= month <= 12
  • 1 <= day <= number of days in the given month and year
  • 0 <= hour < 24
  • 0 <= minute < 60
  • 0 <= second < 60
  • 0 <= microsecond < 1000000
  • fold in [0, 1]

Note: Passing an argument other than an integer will raise a TypeError and passing arguments outside the range will raise ValueError.

Example: Creating an instance of the DateTime class

Python3




# Python program to
# demonstrate datetime object
 
from datetime import datetime
 
# Initializing constructor
a = datetime(2022, 10, 22)
print(a)
 
# Initializing constructor
# with time parameters as well
a = datetime(2022, 10, 22, 6, 2, 32, 5456)
print(a)


Output:

2022-10-22 00:00:00
2022-10-22 06:02:32.005456

Class Attributes of DateTime

Let’s see the attributes provided by this class:

Attribute Name

Description

min

The minimum representable DateTime

max

The maximum representable DateTime

resolution

The minimum possible difference between datetime objects

year

The range of year must be between MINYEAR and MAXYEAR

month

The range of month must be between 1 and 12

day

The range of days must be between 1 and the number of days in the given month of the given year

hour

The range of hours must be between 0 and 24 (not including 24)

minute

The range of minutes must be between 0 and 60 (not including 60)

second

The range of second must be between 0 and 60 (not including 60)

microsecond

The range of microseconds must be between 0 and 1000000 (not including 1000000)

tzinfo

The object containing timezone information

fold

Represents if the fold has occurred in the time or not

Example: Getting the minimum and maximum representable DateTime object

Python3




from datetime import datetime
 
# Getting min datetime
mindatetime = datetime.min
print("Min DateTime supported", mindatetime)
 
# Getting max datetime
maxdatetime = datetime.max
print("Max DateTime supported", maxdatetime)


Output:

Min DateTime supported 0001-01-01 00:00:00
Max DateTime supported 9999-12-31 23:59:59.999999

The now() Method

We can get the current date and time using the now() method of the datetime module.

Python3




from datetime import datetime
 
# Getting Today's Datetime
today = datetime.now()
 
# Accessing Attributes
print("Day: ", today.day)
print("Month: ", today.month)
print("Year: ", today.year)
print("Hour: ", today.hour)
print("Minute: ", today.minute)
print("Second: ", today.second)


Output:

Day:  16
Month: 6
Year: 2023
Hour: 5
Minute: 28
Second: 47

DateTime Class Functions

The DateTime class provides various functions to deal with the DateTime objects. We can convert the DateTime object to string and string to DateTime objects, we can also get the weekday for the particular day of the week of the particular month, we can also set the time zone for a particular DateTime object, etc.

List of DateTime Class Methods

Let us see a few methods provided by the DateTime class in Python.

Function Name

Description

astimezone()

Returns the DateTime object containing timezone information.

combine()

Combines the date and time objects and returns a DateTime object

ctime()

Returns a string representation of the date and time

date()

Return the Date class object

fromisoformat()

Returns a datetime object from the string representation of the date and time

fromordinal()

Returns a date object from the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1. The hour, minute, second, and microsecond are 0

fromtimestamp()

Return date and time from POSIX timestamp

isocalendar()

Returns a tuple year, week, and weekday

isoformat()

Return the string representation of the date and time

isoweekday()

Returns the day of the week as an integer where Monday is 1 and Sunday is 7

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

toordinal()

Return the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1

tzname()

Returns the name of the timezone

utcfromtimestamp()

Return UTC from POSIX timestamp

utcoffset()

Returns the UTC offset

utcnow()

Return current UTC date and time

weekday()

Returns the day of the week as an integer where Monday is 0 and Sunday is 6

Example 1: Getting Today’s Date

Python3




from datetime import datetime
 
# Getting Today's Datetime
today = datetime.now()
print("Today's date using now() method:", today)
 
today = datetime.today()
print("Today's date using today() method:", today)


Output:

Today's date using now() method: 2023-06-16 05:30:57.195635
Today's date using today() method: 2023-06-16 05:30:57.196321

Example 2: Getting DateTime from timestamp and ordinal.

Python3




from datetime import datetime
 
# Getting Datetime from timestamp
date_time = datetime.fromtimestamp(1887639468)
print("Datetime from timestamp:", date_time)
 
# Getting Datetime from ordinal
date_time = datetime.fromordinal(737994)
print("Datetime from ordinal:", date_time)


Output:

Datetime from timestamp: 2029-10-25 16:17:48
Datetime from ordinal: 2021-07-23 00:00:00

Note: For more information on Python Datetime, refer to Python Datetime Tutorial



Previous Article
Next Article

Similar Reads

How to convert a Python datetime.datetime to excel serial date number
This article will discuss the conversion of a python datetime.datetime to an excel serial date number. The Excel "serial date" format is actually the number of days since 1900-01-00. The strftime() function is used to convert date and time objects to their string representation. It takes one or more inputs of formatted code and returns the string r
3 min read
How to Fix - "datetime.datetime not JSON serializable" in Python?
In this article, we are going to learn how to fix the error "datetime.datetime not JSON serializable" in Python. datetime.datetime is a class in the Python datetime module that represents a single point in time. This class is not natively supported by the JSON (JavaScript Object Notation) format, which means that we cannot serialize a datetime.date
4 min read
fromisoformat() Function Of Datetime.date Class In Python
The fromisoformat() function is used to constructs a date object from a specified string that contains a date in ISO format. i.e., yyyy-mm-dd. Syntax: @classmethod fromisoformat(date_string) Parameters: This function accepts a parameter which is illustrated below: date_string: This is the specified ISO format i.e., yyyy-mm-dd date string whose date
2 min read
isocalendar() Function Of Datetime.date Class In Python
The isocalendar() function is used to return a tuple containing ISO Year, ISO Week Number, and ISO Weekday. Note: According to ISO standard 8601 and ISO standard 2015, Thursday is the middle day of a week.Therefore, ISO years always start with Monday.ISO years can have either 52 full weeks or 53 full weeks.ISO years do not have any fractional weeks
2 min read
fromtimestamp() Function Of Datetime.date Class In Python
The fromtimestamp() function is used to return the date corresponding to a specified timestamp. Note: Here the timestamp is ranging from the year 1970 to the year 2038, and this function does not consider leap seconds if any present in the timestamp. This function is a class method. Syntax: @classmethod fromtimestamp(timestamp) Parameters: This fun
2 min read
ctime() Function Of Datetime.date Class In Python
The ctime() function is used to return a string containing the date and time. Syntax: ctime() Parameters: This function does not accept any parameter. Return values: This function returns a string containing the date and time. The format of the string representation: The string is of 24-character length.Week is printed as a three-letter word.Sun, M
2 min read
Isoweekday() Method Of Datetime Class In Python
Isoweekday() is a method of the DateTime class that tells the day of the given date. It returns an integer that corresponds to a particular day. Syntax: datetime.isoweekday() Parameters: None Return Value: It returns an integer which corresponds to a day as per the table Integer ReturnedDay of the week1Monday2Tuesday3Wednesday4Thursday5Friday6Satur
3 min read
Isoformat() Function Of Datetime.date Class In Python
The Isoformat() function is used to return a string of date, time, and UTC offset to the corresponding time zone in ISO 8601 format. The standard ISO 8601 format is all about date formats for the Gregorian calendar. This format prescribes that a calendar date needs to be represented using a 4-digit year followed by a two-digit month and a two-digit
3 min read
timetuple() Function Of Datetime.date Class In Python
timetuple() method returns a time.struct time object which is a named tuple. A named tuple object has attributes that may be accessed by an index or a name. The struct time object has properties for both the date and time fields, as well as a flag that specifies whether or not Daylight Saving Time is in effect. The year, month, and day fields of th
2 min read
weekday() Function Of Datetime.date Class In Python
The weekday() of datetime.date class function is used to return the integer value corresponding to the specified day of the week. Syntax: weekday() Parameters: This function does not accept any parameter. Return values: This function returns the integer mapping corresponding to the specified day of the week. Below table shows the integer values cor
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg