Python datetime

Although a date is not a data type in Python, we may use the datetime module to work with date objects. For example, import the datetime module and use the following code to display the current date:

import datetime

_date = datetime.datetime.now()

print(_date)

When we run the code from the previous example, we get the following resultant date:

Resultant date produced
Resultant date produced

The components included in the date include the following

  • year,
  • month,
  • day,
  • hour,
  • minute,
  • second, and microsecond.

Many methods in the datetime module return information about the date object. Here are a few samples of what you’ll learn about later in this article:

Example: Return the year and name of a weekday

import datetime

_date = datetime.datetime.now()

print(_date.year)
print(_date.strftime("%%A"))
year and name of a weekday
year and name of a weekday

Date Objects: How to create Them

The datetime module’s datetime() class (constructor) is used to produce a date. The datetime() class requires three parameters: year, month, and day to generate a date.

Example :

import datetime

_date = datetime.datetime(2022, 1, 12)

print(_date)


creating a date object
creating a date object

Time and timezone parameters (hour, minute, second, microsecond, tzone) are likewise available in the datetime() class, although optional and have a default value of 0. (None for timezone).

The strftime() method

The strftime() method is used to calculate the time in seconds. A technique for formatting date objects into readable strings is available in the datetime object. strftime() is the method’s name, and it has only one parameter, format, which specifies the format of the returned string:

import datetime

_date = datetime.datetime(2022, 1, 1)

print(_date.strftime("%%B"))
The strftime() method
The strftime() method

To work with dates and times, Python has a module called datetime. Before we go any further, let’s make a couple of simple programs that deal with date and time.

Get the Current Date and Time

import datetime

datetime_object = datetime.datetime.now()
print(datetime_object)
Get the Current Date and Time
Get the Current Date and Time

Datetime class is one of the classes defined in the datetime module. We’ve used the import datetime statement to import the datetime module. We then created a datetime object with the current local date and time using the now() function.

Get Current Date

import datetime

date_object = datetime.date.today()
print(date_object)

We utilized the date class’s today() function to acquire a date object holding the current local date in this program. Alternatively, using today’s class method, you may generate a date object that contains the current date. Here’s how to do it:

from datetime import date
date_today = date.today()
print("Current date =", date_today)

What is the content of datetime?

We can use the dir() function to acquire a list of all a module’s characteristics.

import datetime
print(dir(datetime))
content of datetime

In the datetime module, the following classes are frequently used:

  • date Class
  • time Class
  • datetime Class
  • timedelta Class
  • datetime.date Class

The date class is used to create date objects. A date object represents a date with the following parameters year, month, and day.

Date object representing a date

import datetime

_date = datetime.date(2022, 1, 1)
print(_date)
Date object representing a date
Date object representing a date

If you’re wondering, date() is a constructor of the date class in the previous example. Three arguments are passed to the constructor: year, month, and day. A date object is represented by the variable _a_time. Only the datetime module’s date class is imported. Here’s how to do it:

from datetime import date

_a_time = date(2019, 4, 13)
print(_a_time)

Get a date from a timestamp

A timestamp can also be used to build date objects. The amount of seconds between a given date and January 1, 1970, at UTC is known as a Unix timestamp. The fromtimestamp() method is used to convert a timestamp to date.

from datetime import date

timestamp = date.fromtimestamp(1326244364)
print("Date =", timestamp)

How to Print today’s year, month, and day

From the date object, we can extract the year, month, day, day of the week, etc. Here’s how to do it:

from datetime import date

# date object of today's date

date_today = date.today()

print("Current year:", date_today.year)
print("Current month:", date_today.month)
print("Current day:", date_today.day)


datetime.time -The local time is represented by a time object created from the time class.

Represent the time using the Time object

from datetime import time

# initialize time as hour = 0, minute = 0, second = 0

_a_time = time()
print("a =", _a_time)

# set the time as hour, minute and second
_b_time = time(8, 56, 20)
print("b =", _b_time)

# set the time as hour, minute and second
_c_time = time(hour = 8, minute = 56, second = 20)
print("c =", _c_time)

# time(hour, minute, second, microsecond)

d = time(8, 56, 20, 234566)
print("d =", d)

Display the time in hours, minutes, seconds, and microseconds

Once you’ve created it, you can quickly print the attributes of a time object, such as the hour, minute, and so on.

from datetime import time

_a_time = time(8, 56, 20)

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

datetime.datetime – Dateclass is a class in the datetime module that can hold data from the date and time objects.

How to use Python’s datetime object

from datetime import datetime

# initialize datetime as year, month, and day
_a_time = datetime(2022, 1, 12)
print(_a_time)

# initialize datetime as year, month, day, hour, minute, second, and microseconds

_b_time = datetime(2022, 8, 56, 34, 58, 22, 342380)
print(_b_time)


The datetime() constructor’s first three arguments, year, month, and the day is required.

Print the year, month, hour, minute, and timestamp

from datetime import datetime

_a_time = datetime(2022, 1, 12, 23, 55, 59, 342380)
print("year =", _a_time.year)
print("month =", _a_time.month)
print("hour =", _a_time.hour)
print("minute =", _a_time.minute)
print("timestamp =", _a_time.timestamp())
Print the year, month, hour, minute, and timestamp
Print the year, month, hour, minute, and timestamp

datetime.timedelta – The variation between two given dates or times is denoted using the timedelta object.

Compare and contrast two dates and times

from datetime import datetime, date

the_time1 = date(year = 2018, month = 7, day = 12)
the_time2 = date(year = 2017, month = 12, day = 23)
the_time3 = the_time1 - the_time2
print("the_time3 =", the_time3)

the_time4 = datetime(year = 2018, month = 7, day = 12, hour = 7, minute = 9, second = 33)
the_time5 = datetime(year = 2019, month = 6, day = 10, hour = 5, minute = 55, second = 13)
the_time6 = the_time4 - the_time5
print("the_time6 =", the_time6)

print("type of the_time3 =", type(the_time3))
print("type of the_time6 =", type(the_time6))

What is the difference between two timedelta objects

from datetime import timedelta

the_time1 = timedelta(weeks = 2, days = 5, hours = 1, seconds = 33)
the_time2 = timedelta(days = 4, hours = 11, minutes = 4, seconds = 54)
the_time3 = the_time1 - the_time2

print("the_time3 =", the_time3)

How to print negative timedelta object

from datetime import timedelta

the_time1 = timedelta(seconds = 33)
the_time2 = timedelta(seconds = 54)
the_time3 = the_time1 - the_time2

print("the_time3 =", the_time3)
print("the_time3 =", abs(the_time3))
How to print negative timedelta object
printing negative timedelta object

Time length in seconds

The total_seconds() method returns the cumulative number of seconds in a timedelta object.

from datetime import timedelta

the_time = timedelta(days = 5, hours = 1, seconds = 33, microseconds = 233423)
print("total seconds =", the_time.total_seconds())

The + operator is also be used to find the sum of two dates and times. Integers and floats are also be used to multiply and divide a timedelta object.

Python datetime format

Date and time are represented differently in different regions, organizations, etc. In the United States, mm/dd/yyyy is more frequent, while dd/mm/yyyy is more popular in the United Kingdom. To handle this, Python includes strftime() and strptime() functions. strftime() converts a datetime object to a string in Python.

The strftime() method is found in the date, datetime, and time classes. The method converts a date, datetime, or time object into a formatted string.

How to Format the date using strftime()

from datetime import datetime

# current date and time

now = datetime.now()
the_time = now.strftime("%%H:%%M:%%S")
print("time:", the_time)

string_time_format1 = now.strftime("%%m/%%d/%%Y, %%H:%%M:%%S")

# mm/dd/YY H:M:S format

print("string time1:", string_time_format1)
string_time_format2 = now.strftime("%%d/%%m/%%Y, %%H:%%M:%%S")

# dd/mm/YY H:M:S format

strptime()

strptime() is a Python function that converts a string to a datetime. The strptime() method converts a string into a datetime object (representing date and time).

from datetime import datetime

date_string = "12 January, 2022"
print("date_string =", date_string)

date_object = datetime.strptime(date_string, "%%d %%B, %%Y")
print("date_object =", date_object)


strptime()
strptime()

Two arguments are passed to the strptime() method:

  • a string that corresponds to the first argument’s date and time format code
  • By the way, the format codes for the day, month(full name), and year are %d, %B, and %Y, respectively.

Conclusion

Although date and time aren’t data types in Python, a module called datetime is imported to work with both the date and the time. There is no need to install the Python Datetime module outside because it is included in Python.

The Python Datetime package provides classes for manipulating 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 you’re altering objects rather than strings or timestamps when you manipulate them.

Similar Posts

Leave a Reply

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