Python Datetime With 6 Main Classes And Examples

Introduction

Date and time are not data types in Python. However, a module called DateTime may be imported to deal with both the date and the time. There is no need to install the Python Datetime module outside because it is built into Python.

The Python Datetime module provides classes for working with dates and times. These classes offer a variety of capabilities for working with dates, times, and time intervals. In Python, date and DateTime are objects, so when you handle them. You are actually handling objects rather than strings or timestamps.

The DateTime module is categorized into 6 main classes:

  1. date : An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect. Its attributes are year, month, and day.
  2. time : An idealized time, independent of any particular day, assuming that every day has exactly 246060 seconds. Its attributes are hour, minute, second, microsecond, and tzinfo.
  3. datetime : It’s a combination of date and time along with the attributes year, month, day, hour, minute, second, microsecond, and tzinfo.
  4. timedelta : A duration expressing the difference between two date, time, or DateTime instances to microsecond resolution.
  5. tzinfo : It provides time zone information objects.
  6. timezone : A class that implements the tzinfo abstract base class as a fixed offset from the UTC (New in version 3.2).

Class 01: Python DateTime Date Class

Python’s date class is used to create date objects. When this class’s object is created, it represents a date in the format YYYY-MM-DD. The constructor of this class needs three mandatory arguments year, month, and date.

Constructor Syntax:

class datetime.date(year, month, day)

The arguments must be in the following range:

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

Note: If the argument is not an integer it will raise a TypeError and if it is outside the range a ValueError will be raised.

Code Example 01: Date object representing date in Python

# Python program to demonstrate date class
# import the date class
from datetime import date

# initializing constructor and passing arguments in the format year, month, date
my_date1 = date(1999, 3, 5)
print("Date passed as argument is", my_date1)

Output:

Date passed as argument is 1999-03-05

Code Example 02: Errors that you will get during date object

# Python program to demonstrate date class
# import the date class
from datetime import date

# initializing constructor and passing arguments in the format year, month, date
# will raise an ValueError as date is outside range
my_date2 = date(1999, 3, 69)
print(my_date2)

# will raise a TypeError as a string is passed instead of integer
my_date3 = date('1999', 3, 5)
print(my_date3)

# will raise a Error of leading zeros
my_date4 = date(1999, 03, 05)
print("Date passed as argument is", my_date4)

Code Example 03: Get Current Date

The date class’s today() method is used to return the current local date. The today() method has various parameters (year, month, and day). These can be printed individually.

# Python program to print current date
# import the date class
from datetime import date

# function of date class
today = date.today()

print("Today's date is", today)

Output:

Today's date is 2022-05-25

Code Example 04: Get Today’s Year, Month, and Date

We can get the year, month, and date attributes from the date object using the year, month, and date attribute of the date class.

# import the date class
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)

Output:

Current year: 2022
Current month: 5
Current day: 25

Code Example 05: Get Time from timestamp

We can create date objects from timestamps y=using the fromtimestamp() method. The timestamp is the number of seconds from 1st January 1970 at UTC to a particular date.

# import the date class
from datetime import datetime

# Getting Datetime from timestamp
date_time = datetime.fromtimestamp(1434323424)
print("Datetime from timestamp:", date_time)

Output:

Datetime from timestamp: 2015-06-14 23:10:24

Code Example 06: Convert Date to String

We can convert the date object to a string representation using two functions isoformat() and strftime().

# import the date class
from datetime import date

# function of date class
today = date.today()

# Converting the date to the string
Str = date.isoformat(today)
print("String Representation", Str)
print(type(Str))

Output:

String Representation 2022-05-25
<class 'str'>

Date Class Methods

MethodDescription
ctime()Return a string representing the date
fromisocalendar()It Returns a date corresponding to the ISO calendar
fromisoformat()Returns a date object from the string representation of the date
frommordinal()It Returns a date object from the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1
fromtimestamp()Returns a date object from the POSIX timestamp
isocalendar()It Returns a tuple year, week, and weekday
isoformat()Returns the string representation of the date
isoweekday()It Returns the day of the week as an integer where Monday is 1 and Sunday is 7
replace()Changes the value of the date object with the given parameter
strftime()It Returns a string representation of the date with the given format
timetuple()Returns an object of type time.struct_time
today()It returns the current local date
toordinal()Return the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1
weekday()Returns the day of the week as an integer where Monday is 0 and Sunday is 6

Class 02: Python DateTime Time Class

The time class creates the time object which represents local time, independent of any day.

Constructor Syntax:

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

All the arguments are optional. tzinfo can be None otherwise all the attributes must be an integer in the following range:

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

Code Example 01:

# Python program to demonstrate time class
# import the date class
from datetime import time

# calling the constructor
my_time = time(16, 1, 5)
print("Entered time", my_time)

# Calling constructor with 0 argument
my_time = time()
print("\nTime without argument", my_time)

# calling constructor with minute argument
my_time = time(minute=1)
print("\nTime with one argument", my_time)

# calling constructor with hour argument
my_time = time(hour=8)
print("\nTime with one argument", my_time)

# calling constructor with minute argument
my_time = time(second=5)
print("\nTime with one argument", my_time)

Output:

Entered time 16:01:05

Time without argument 00:00:00

Time with one argument 00:01:00

Time with one argument 08:00:00

Time with one argument 00:00:05

Code Example 02: Errors that you will get in the Time class

# Python program to demonstrate time class
# import the date class
from datetime import time

# will rase an ValueError as it is out of range
my_time = time(hour = 26)
print("my_time)

# will raise TypeError as string is passed instead of int
my_time = time(hour ='23')
print("my_time)

Code Example 03: Get hours, minutes, seconds, and microseconds

After creating a time object, its attributes can also be printed separately.

# Python program to demonstrate time class
# import the date class
from datetime import time

Time = time(8, 5, 56, 12)

print("hour =", Time.hour)
print("minute =", Time.minute)
print("second =", Time.second)
print("microsecond =", Time.microsecond)

Output:

hour = 8
minute = 5
second = 56
microsecond = 12

Code Example 04: Convert Time object to String

We can convert a time object to a string using the isoformat() method.

# Python program to demonstrate time class
# import the date class
from datetime import time

# Creating Time object
Time = time(12,24,36,232)

# Converting Time object to string
Str = Time.isoformat()
print("String Representation:", Str)
print(type(Str))

Output:

String Representation: 12:24:36.000232
<class 'str'>

Time Class Methods

MethodsDescription
dst()Returns tzinfo.dst() is tzinfo is not None
fromisoformat()Returns a time object from the string representation of the time
isoformat()It Returns the string representation of time from the time object
replace()Changes the value of the time object with the given parameter
strftime()It returns a string representation of the time with the given format
tzname()Returns tzinfo.tzname() is tzinfo is not None
utcoffset()It Returns tzinfo.utcffsets() is tzinfo is not None

Class 03: Python DateTime Class

The Python DateTime class contains date and time information. Datetime, like a date object, assumes the current Gregorian calendar is extended in both directions; DateTime, like a time object, assumes every day has exactly 3600*24 seconds.

Syntax:

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. tzinfo can be None, the rest all the attributes must be an integer in the following range:

  • MINYEAR <= year <= MAXYEAR
  • 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 integer will raise a TypeError and passing arguments outside the range will raise ValueError.

Code Example 01: DateTime object representing DateTime in Python

# Python program to demonstrate datetime object
# import datetime class
from datetime import datetime

# Initializing constructor
my_date1 = datetime(1999, 3, 5)
print(my_date1)

# Initializing constructor with the time aslo
my_date2 = datetime(1999, 3, 5, 9, 11, 59, 342380)
print(my_date2)

Output:

1999-03-05 00:00:00
1999-03-05 09:11:59.342380

Code Example 02: Python Datetime Get year, month, hour, minute, and timestamp

After creating a DateTime object, its attributes can also be printed separately.

# Python program to demonstrate datetime object
# import datetime class
from datetime import datetime

my_datetime = datetime(1999, 3, 8, 23, 32, 12)

print("year =", my_datetime.year)
print("month =", my_datetime.month)
print("day =", my_datetime.day)
print("hour =", my_datetime.hour)
print("minute =", my_datetime.minute)
print("timestamp =", my_datetime.timestamp())

Output:

year = 1999
month = 3
day = 8
hour = 23
minute = 32
timestamp = 920935932.0

Code Example 03: Current date and time or Python Datetime today

You can print the current date and time using the Python Datetime now function. The now() function returns the current local date and time.

# Python program to demonstrate datetime object
# import datetime class
from datetime import datetime

# Calling now() function
today = datetime.now()

print("Current date and time is", today)

Output:

Current date and time is 2022-05-26 11:12:40.833710

Code Example 04: Convert Python Datetime to String

We can convert Datetime to string in Python using the Python DateTime strftime and Python DateTime isoformat methods.

# Python program to demonstrate datetime object
# import datetime class
from datetime import datetime as date

# Getting current date and time
now = date.now()

string = date.isoformat(now)
print(string)
print(type(string))

Output:

2022-05-26T11:16:28.666796
<class 'str'>

Python Datetime Format

Datetime formatting is important since date representation varies from place to place. In some countries, the format is yyyy-mm-dd, whereas, in others, it is dd-mm-yyyy. Python Datetime may be formatted using the Python DateTime strptime and python DateTime strftime methods.

Code Example: Datetime format

# Python program to demonstrate strftime() function
from datetime import datetime as date

# Getting current date and time
now = date.now()
print("Without formatting", now)

# Example 1
s = now.strftime("%A %m %-Y")
print('\nExample 1:', s)

# Example 2
s = now.strftime("%a %-m %y")
print('\nExample 2:', s)

# Example 3
s = now.strftime("%-I %p %S")
print('\nExample 3:', s)

# Example 4
s = now.strftime("%H:%M:%S")
print('\nExample 4:', s)

Output:

Without formatting 2022-05-26 12:30:27.940048
Example 1: Thursday 05 2022
Example 2:Thu 5 22
Example 3:12 PM 27
Example 4: 12:30:27

Python Datetime strftime

strftime() method converts the given date, time or datetime object to the a string representation of the given format.

Code Example: DateTime strptime

# import datetime module from datetime
from datetime import datetime

# consider the time stamps from a list in string
# format DD/MM/YY H:M:S.micros
time_data = ["25/05/99 02:35:8.023", "26/05/99 12:45:0.003",
			"27/05/99 07:35:5.523", "28/05/99 05:15:55.523"]

# format the string in the given format : day/month/year
# hours/minutes/seconds-micro seconds
format_data = "%d/%m/%y %H:%M:%S.%f"

# Using strptime with datetime we will format string
# into datetime
for i in time_data:
	print(datetime.strptime(i, format_data))

Output:

1999-05-25 02:35:08.023000
1999-05-26 12:45:00.003000
1999-05-27 07:35:05.523000
1999-05-28 05:15:55.523000

Handling Python DateTime timezone

Timezones in DateTime may be used to show time-based on the timezone of a certain place. This is possible with Python’s pytz package. This module provides date-time conversion functionality and helps users who service international clients.

Code Example:

from datetime import datetime
from pytz import timezone

format = "%Y-%m-%d %H:%M:%S %Z%z"

# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print(now_utc.strftime(format))

timezones = ['Asia/Dhaka', 'Europe/Berlin', 'America/Los_Angeles']

for tzone in timezones:

	# Convert to Asia/Dhaka time zone
	now_asia = now_utc.astimezone(timezone(tzone))
	print(now_asia.strftime(format))

Output:

2022-05-26 12:38:44 UTC+0000
2022-05-26 18:38:44 +06+0600
2022-05-26 14:38:44 CEST+0200
2022-05-26 05:38:44 PDT-0700

DateTime Class Methods

MethodsDescription
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 date and time
date()Return the Date class object
fromisoformat()Returns a DateTime object from the string representation of the date and time
fromordinal()It 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()It 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()It 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()It Returns 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

Class 04: Python DateTime Timedelta Class

The Python timedelta class is used to calculate date differences and may also be used to manipulate dates in Python. It is one of the simplest methods for manipulating dates.

Syntax:

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

Code Example 01: Python DateTime add days to DateTime object

# Timedelta function demonstration
from datetime import datetime, timedelta

# Using current time
time_for_now = datetime.now()

# printing initial_date
print("initial_date", str(time_for_now))

# Calculating future dates
# for two years
future_date_after_1yr = time_for_now + timedelta(days=365)

future_date_after_5days = time_for_now + timedelta(days=5)

# printing calculated future_dates
print('future_date_after_1yr:', str(future_date_after_1yr))
print('future_date_after_5days:', str(future_date_after_5days))

Output:

initial_date 2022-05-26 12:09:42.365978
future_date_after_1yr: 2023-05-26 12:09:42.365978
future_date_after_5days: 2022-05-31 12:09:42.365978

Code Example 02: Difference between two dates and times

# Timedelta function demonstration
from datetime import datetime, timedelta

# Using current time
time_for_now = datetime.now()

# printing initial_date
print("initial_date", str(time_for_now))

# Some another datetime
new_final_time = time_for_now + \
                timedelta(days=2)

# printing new final_date
print("new_final_time", str(new_final_time))


# printing calculated past_dates
print('Time difference:', str(new_final_time - time_for_now))

Output:

initial_date 2022-05-26 12:12:00.719634
new_final_time 2022-05-28 12:12:00.719634
Time difference: 2 days, 0:00:00

timedelta Class Methods

MethodsDescription
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 returns the int of floor value of the output
Modulo (%)It Divides two timedelta objects and returns the remainder
+(timedelta)Returns the same timedelta object
-(timedelta)Returns the resultant of -1*timedelta
abs(timedelta)It Returns the +(timedelta) if timedelta.days > 1=0 else returns -(timedelta)
str(timedelta)Returns a string in the form (+/-) day[s], HH:MM:SS.UUUUUU
repr(timedelta)Returns the string representation in the form of the constructor call

Conclusion

That’s all for this article, if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn

Suggested Articles:

  1. Python Requests Library

Leave a Comment