top

Search

Python Tutorial

.

UpGrad

Python Tutorial

Datetime in Python

Introduction

Many contemporary apps make use of the programming language- python. Because Python has so many incredible modules and functions, it's imperative to learn these capabilities if you're a web developer or data scientist. Read the article to learn Datetime in Python.

Overview

The usage of dates and timings is occasionally recommended while creating a script or machine learning algorithm. Dates and times can be expressed in a variety of ways in daily life, such as July 4, March 8, 2022, or December 31, 2022, 23:59:59.  Thankfully, the language Python has the datetime module, which allows us to control objects representing dates and times quickly.

What is Datetime in Python?  

The datetime module in the Python language is a standalone unit. This indicates that there aren't two distinct data kinds. This datetime module may be imported to make them operate with dates and times. Python has a built-in module called datetime. No extra installation is required on the part of developers. 

What is the Import Datetime Statement?  

If you want to import datetime in Python, keep in mind that it is rather straightforward. If you wish to import a specific class from the datetime module, such as date, time, datetime, timedelta, and so on, follow these steps: 

# importing the date class 
from datetime import date 
# importing the time class 
from datetime import time
# importing the datetime class 
from datetime import datetime

Python DateTime module (Explain with examples, screenshots, images)

What are the Common  Classes in the Datetime Module?  

When it comes to datetime in Python, there are six primary classes to consider. To learn more about them, continue with this section: 

Date 

We refer to dates in the Gregorian calendar as "dates." The date class in Python is introduced quite clearly using characteristics such as day, month, and year. 

Time 

The next class addressed here is time. This class does not depend on the day. Each day is supposed to have 24*60*60 seconds in this context. In Python, the time class has the following attributes: minute, second, microsecond, hour, and tzinfo. 

Datetime

In Python, datetime is the combination of dates and times. This class's properties are identical to those of the date and distinct classes. Among the properties are day, month, year, minute, second, microsecond, hour, and tzinfo. 

Timedelta 

Timedelta may be defined as the difference in microsecond precision between two distinct dates, times, or datetime instances. 

Tzinfo

tzinfo is only an attribute. It may supply you with various timezone-related data elements. 

Timezone 

This class can use the tzinfo abstract base class with a specified offset from UTC. You are now viewing the new UTC version 3.2. 

Get the Current Date 

The date class's today() method is used to return the current local date. The year, month, and day are three of the characteristics available in today's () method. These may each be printed separately. 

# Python program to
# print current date
from datetime import date
# calling the today
# function of date class
today = date.today()
print("Today's date is, "today)

Output: Today's date is 2023-04-10

Get Today’s Year, Month, and Date 

The date class's year, month, and date attribute allows us to retrieve the year, month, and date characteristics from the date object.

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: 2023 Current month: 10 Current day: 04

Get Date from Timestamp 

With the help of the fromtimestamp() function, data objects may be produced from timestamps. The timestamp is the duration from 00:00:00 UTC on January 1st to a certain date.

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

Output

Datetime from timestamp: 2029-10-25 16:17:48

Convert Date to String 

A date object can be converted to a string representation utilizing the methods isoformat() and strftime().

from datetime import date

# calling the today
# 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 2021-08-19

<class 'str'>

List of Date Class Methods 

Function Name 

Description

ctime()

Return a string containing the date.

fromisocalendar()

This function returns a date corresponding to the ISO calendar.

fromisoformat()

Generate a date object from the date's string representation.

fromordinal()

provides a date object returned from the proleptic Gregorian ordinal, in which January 1 of a given year has ordinal 1.

fromtimestamp()

provides a date object from the POSIX timestamp

isocalendar()

provides a tuple year, week, and weekday

isoformat()

provides the string representation of the date

isoweekday()

The day of the week is returned as an integer, with Monday being 1. Sunday being 7.

replace()

modify the value of the date object using the specified argument.

strftime()

returns a string containing a date representation in the specified format.

timetuple()

provides an object of type time.struct_time

today()

provides the current local date

toordinal()

Return the date's proleptic Gregorian ordinal, with January 1 of year 1 having ordinal 1.

weekday()

provides an integer day of the week with Monday being 0 and Sunday being 6.

Python Time class

Example 1: Time object representing time in Python. 

In Python, the time class allows you to represent time. You can create a time object with hours, minutes, seconds, and microseconds.

 Here's an example:

 import datetime
# Create a time object with hours, minutes, seconds, and microseconds
time_obj = datetime.time(14, 30, 45, 500000)
# Display the time object
print(time_obj)

Output:

14:30:45.500000

In this example, we import the datetime module and create a time object with the time values specified (hours=14, minutes=30, seconds=45, microseconds=500000). The time object is then printed, showing the time in the specified format.

Example 2: Get hours, minutes, seconds, and microseconds.

Using attributes, you can access a time object's individual components (hours, minutes, seconds, microseconds). Here's an example:

import datetime
# Create a time object
time_obj = datetime.time(9, 15, 30, 750000)
# Access and print individual components
hours = time_obj.hour
minutes = time_obj.minute
seconds = time_obj.second
microseconds = time_obj.microsecond
print(f"Hours: {hours}")
print(f"Minutes: {minutes}")
print(f"Seconds: {seconds}")
print(f"Microseconds: {microseconds}")

Output: 

Hours: 9
Minutes: 15
Seconds: 30
Microseconds: 750000

In this example, we create a time object and then access its attributes (hour, minute, second, and microsecond) to retrieve and print each component individually.

List of Time Class Methods 

Function Name

Description

dst()

provides tzinfo.dst() is tzinfo is not None

fromisoformat()

provides a time object from the string representation of the time

isoformat()

provides the string representation of time from the time object

replace()

Changes the value of the time object with the given parameter

strftime()

provides a string representation of the time with the given format

tzname()

provides tzinfo.tzname() is tzinfo is not None

utcoffset()

provides tzinfo.utcffsets() is tzinfo is not None

Python Datetime Class 

Date and time data are both included in the DateTime class. Similar to a date object, datetime makes the assumption that the Gregorian calendar is stretched in both directions and that each day has precisely 3600*24 seconds.

List of Datetime Class Methods

Let's look at some of the Datetime class methods in Python.

Function Name

Description

astimezone()

provides the DateTime object containing timezone information.

combine()

Returns a DateTime object after combining the date and time elements.

ctime()

provides a string representation of the date and time

date()

provides the Date class object

fromisoformat()

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

fromordinal()

provides 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()

provides date and time from POSIX timestamp

isocalendar()

provides 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 weekday as an integer, where Monday is 0, and Sunday is 6.


Python Timedelta Class 

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

Operations Supported by Timedelta Class 

Operator

Description

Addition ( )

Adds and returns two timedelta objects

Subtraction (-)

Subtracts and returns two timedelta objects

Multiplication (*)

Multiplies the timedelta object by a float or an int. 

Division (/)

The timedelta object is divided by float or int.


Floor division (//)

provides an integer representation of the output's floor value after dividing the timedelta object by a float or int. 


Modulo (%)

Returns the remainder of dividing two timedelta objects.


(timedelta)

gives the same timedelta object

-(timedelta)

gives the resultant of -1*timedelta

abs(timedelta)

if timedelta.days > 1=0, then returns the (timedelta). else gives -(timedelta).

str(timedelta)

gives a string in the form ( /-) day[s],  HH:MM:SS.UUUUUU

repr(timedelta)

provides the constructor call that represents the string representation.

Python DateTime.tzinfo() 

There is no time zone data in the datetime.now() method. Only the current system time is used. Python has an abstract base class called Tzinfo. It cannot be constructed directly. This abstract class must be descended from in order for a concrete subclass to implement its available methods. 

Python DateTime Timezone 

When displaying time according to a certain region's timezone, DateTime's timezones feature can be utilized. Python's pytz package may be used for this. This module assists worldwide customer base users by providing date-to-time conversion features.

Here is a list of all the functions this class offers: 

List of all Date Class functions

Function Name 

Description

ctime()

Provides a string representing the date

fromisocalendar()

Provides a date corresponding to the ISO calendar

fromisoformat()

Provides a date object from the string representation of the date

fromordinal()

gives a date object based on the proleptic Gregorian ordinal, whereas January 1 of a given year has ordinal 1.

fromtimestamp()

Provides a date object from the POSIX timestamp

isocalendar()

Provides a tuple year, week, and weekday

isoformat()

Provides the string representation of the date

isoweekday()

Provides an integer day of the week with Monday being 1 and Sunday being 7.


replace()

Changes the value of the date object with the given parameter

strftime()

Provides a string representation of the date with the given format

timetuple()

Provides an object of type time.struct_time

today()

Provides the current local date

Example 1: Getting the current date and also changing the date to string.

# Python program to
# print current date
 from datetime import date
 # calling the today
# function of date class
today = date.today()
 print("Today's date is," today)
 # Converting the date to the string
Str = date.isoformat(today)
print("String Representation," Str)
print(type(Str))

Output

Today's date is 2021-07-23
String Representation 2021-07-23
<class 'str'>

Conclusion

Python is one of the most popular languages adopted today, and it has numerous uses in cutting-edge fields like data science and analytics. Python is an important skill to have if you want to pursue a career in data science. We really hope you found this tutorial on "datetime in Python" helpful. 

FAQs

1. What does a Python datetime mean?

datetime.Datetime: This symbol denotes a time point that includes both the date and the time.

2. How can you change a string into a date and time?

To turn a string into a datetime object in Python, use the datetime- strptime() function. 

Leave a Reply

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