Modules Python

Datetime in Python

Datetime in Python

Introduction

The datetime package in Python is a useful collection of utilities for handling dates and times. You may fulfill the majority of your datetime processing requirements with just the five approaches I'm about to demonstrate.

Wrangling dates and times in python

The datetime package in Python is a useful collection of utilities for handling dates and times. You can take care of the majority of your datetime processing demands with only the five strategies I'm about to teach you.

It's beneficial to look at the construction of datetime before continuing. A datetime object is the basic building piece. It should come as no surprise that this combines a date object and a time object. A date object is nothing more than a group of methods that can handle them together with a set of values for the year, month, and day. A time object has a comparable structure. It includes values for the time zone, the hour, the minute, the second, and the microsecond. By correctly selecting these values, any time may be represented.

combine()

# importing the pandas library
import pandas as pd

# importing the date and time module
from datetime import date,time

#create a timestamp object from date and time combination
my_datetime = pd.Timestamp.combine(date(2015,5,1), time(7,0))

print(my_datetime)


>>> 2015-05-01 07:00:00

This allows us to combine date and time objects to make them. We begin by setting up a time and adding the minutes 0 and 7 to it. This denotes the hour of seven. The second and the microsecond are considered to be 0 since we omitted to provide them. The year, month, and day are then passed to make a date. A datetime may be easily created. In order to create our datetime, we utilize the combine() method and provide it the date object and the time object.

Calls to datetime may be unclear due to the naming pattern. The name of the object, the package, and a module inside the package are all Datetime. So, when we combine our date and time, we refer to it as datetime, which seems unnecessary. datetime prefix. In the first datetime, the package is mentioned, in the second, the module, and in the third, the method combine() is mentioned.

timedelta

# Timedelta function demonstration
from datetime import datetime, timedelta

# Using current time
ini_time_for_now = datetime.now()

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

# Some another datetime
new_final_time = ini_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 - \
                            ini_time_for_now))



>>> initial_date 2023-05-19 13:22:49.076306
    new_final_time 2023-05-21 13:22:49.076306
    Time difference: 2 days, 0:00:00

This shows how two datetimes differ from one another. There are only three values for a timedelta: days, seconds, and microseconds. This is a unique way to represent the difference between any two datetimes. Because they enable us to do straightforward addition and subtraction calculations on datetimes, timedeltas are very helpful. They eliminate the need to consider concepts like the number of days in a month, the number of seconds in a day, and leap years.

Timestamps

For computers, working in days, hours, minutes, and seconds is uncomfortable. There are regulations and exceptions to be aware of. The idea of a UNIX epoch was developed to make working with dates and timings easier. This is the time in Coordinated Universal Time (UTC +0) since the first second of the year 1970 at 12:00 AM. As a result, any date and time may be represented by a single floating point integer that is easy to understand. The only problem is that a human reader would find it difficult to understand. Our human-interpretable datetime object may be transformed to and from a UNIX timestamp using the procedures timestamp() and fromtimestamp().

weekday()

from datetime import datetime

date_time = datetime.fromtimestamp(1887639468)
print("Datetime from timestamp: ",date_time)

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

import datetime
start_datetime = datetime.datetime(2021,8,1,00,00,00)
weekday_number = start_datetime.date().weekday()
print(weekday_number)

>>> 6

The weekday() method determines the day of the week for any date. Call the date() method on your datetime to utilize it. By ignoring the time component, this isolates the date object. Call its weekday() function after that. This outputs a number between 0 and 6, where 0 represents Monday, 1 represents Tuesday, etc., and 6 represents Sunday. It takes care of all the complications associated with keeping track of the days of the week so you don't have to.

Date strings

# Pass a date string and a code for interpreting it.
new_datetime = datetime.datetime.strptime(
    '2018-06-21', '%Y-%m-%d')
# Turn a datetime into a date string.
datestr = new_datetime.strftime('%Y-%m-%d')
print(datestr)

>> "2018-06-21"

The fifth and final trick is the conversion of a date into and out of a string. This is very useful when we wish to convert text dates into datetime objects when ingesting data from a text file. It is useful when we wish to export our datetime object to a text file or make it visible to users. The strptime() and strftime() methods are used to do this. We are required to provide a string that specifies the format when performing a conversion in either direction. '%Y' stands for the year, '%m' for the two-digit month, and '%d' for the two-digit day in this snippet of code.

write your code here: Coding Playground