Basic DateTime Operations in Python | by Munia Humaira | Towards Data Science

Sometimes dealing with data containing date and time can be tedious job to do, thankfully there is this built in way to help us with the work. Python provides a datetime module that enables us to manipulate date and time in many ways.
We need to look at five main object classes in this module, which we will eventually need depending on the work we want to do. After that, we will discuss some examples explaining the tasks of the classes. The classes are as follows -
datetime.date : It allows us to manipulate date without interfering time (month, day, year)datetime.time : It allows us to manipulate date without interfering date (hour, minute, second, microsecond)datetime.datetime : It allows us to manipulate the combination of date and time (month, day, year, hour, second, microsecond).datetime.tzinfo : An abstract class for dealing with time zones. These types of objects are immutable. For instance, to account for different time zones and/or daylight saving times.datetime.timedelta : It is the difference between two date, time or datetime instances; the resolution ca
datetime.date : It allows us to manipulate date without interfering time (month, day, year)
datetime.time : It allows us to manipulate date without interfering date (hour, minute, second, microsecond)
datetime.datetime : It allows us to manipulate the combination of date and time (month, day, year, hour, second, microsecond).
datetime.tzinfo : An abstract class for dealing with time zones. These types of objects are immutable. For instance, to account for different time zones and/or daylight saving times.
datetime.timedelta : It is the difference between two date, time or datetime instances; the resolution ca
As datetime includes enables us to deal with both the date and time, therefore, first let’s see how this object behaves. datetime is both a module and a class within that module. We will import the datetime class from the datetime module and print the current date and time to take a closer look . We can do this using datetime’s .now() function. We’ll print our datetime object.
# import datetime class from datetime modulefrom datetime import datetime# get today's datetoday = datetime.now()print(today)
The output looks like :
Now if we want to see the type then we can write :
print('Type :- ',type(today))
So we see from above today is indeed a datetime object of datetime class.
From above example we can understand that how should date and time objects work. date will work only with dates, excluding the time and time will work vice versa.
dt_nw = datetime.now()# to get hour from datetimeprint('Hour: ', dt_nw.hour)# to get minute from datetimeprint('Minute: ', dt_nw.minute)
From datetime we can also get the day of the week using its . weekday() function as a number . But we can convert that to a text format (i.e. Monday, Tuesday, Wednesday...) using the calendar module and a method called .day_name().
First, we will import calendar module and then find out what is the month and year and the do the above mentioned operations.
# import calendar moduleimport calendarmy_date= datetime.now()# To get month from dateprint('Month: ', my_date.month) # To get month from yearprint('Year: ', my_date.year) # To get day of the monthprint('Day of Month:', my_date.day)# to get name of day(in number) from dateprint('Day of Week (number): ', my_date.weekday())# to get name of day from dateprint('Day of Week (name): ', calendar.day_name[my_date.weekday()])
Now we need to understand two kinds of datetime objects ;
Aware — An aware object has the knowledge that is needed to work with ambiguous time,It contains time zone and daylight saving time informations, so that it can locate itself relative to other aware objects.Naive — This one is easier to work with. Because it doesn’t contain information about different timezones and daylight saving times. The operation merely depends on the program.
Aware — An aware object has the knowledge that is needed to work with ambiguous time,It contains time zone and daylight saving time informations, so that it can locate itself relative to other aware objects.
Naive — This one is easier to work with. Because it doesn’t contain information about different timezones and daylight saving times. The operation merely depends on the program.
For programs requiring aware objects, datetime, date and time objects have an optional time zone information attribute, tzinfo . But tzinfo is an abstract class. Dealing with this, you have to decide exactly which methods are needed. Because it depends totally on the uses made of aware datetime objects.
But handling timezones are made easy by pytz module. It helps us deal with cross-timezone conversions and handles the daylight savings time in locations that use that. Let’s look at the example :
# import timezone from pytz modulefrom pytz import timezone# Create timezone UTCutc = timezone('UTC')# Localize date & timeloc = utc.localize(datetime(2020, 1, 1, 3, 50, 0))print(loc)# Convert localized date & time into Asia/Dhaka timezonedhaka = timezone("Asia/Dhaka")print(loc.astimezone(dhaka))# Convert localized date & time into Europe/Berlin timezoneberlin = timezone('Europe/Berlin')print(loc.astimezone(berlin))
We have used the localize() function to add a time zone location to a datetime object . The function astimezone() converts the existing local time zone into any other specified time zone.
Sometimes in a program we may need to specify the remaining time or a time span. In that case we can always use timedelta objects. We can use this to manipulate dates or times by adding and subtracting from them. Let’s look at some examples :
#import timedeltafrom datetime import timedeltaprint(timedelta(days= 365, hours= 12, minutes= 30))
# get current timenow = datetime.now()print ("Today's date & time: ", str(now))#add 365 days to current datefuture_date_after_one_year = now + timedelta(days = 365)print('Date & time after one year: ', future_date_after_one_year)#subtract 7 days from current dateseven_days_ago = now - timedelta(days = 7)print('Date & time seven days ago: ', seven_days_ago)# print('seven_days_ago object type: ', type(seven_days_ago))
So this is how we can work with timedelta objects. In most of the scientific scripts / cases, delta always means the difference between two things.
datetime includes two methods, strptime() and strftime(), for converting objects from strings to datetime objects and vice versa. strptime() can read strings with date and time information and convert them to datetime objects, and strftime() converts datetime objects back into strings.
# import datetimefrom datetime import datetimedate_str = "2 january, 2020"# format datedate_obj = datetime.strptime(date_str, "%d %B, %Y")print("Today's date is: ", date_obj)
Now let’s see the use of strftime() :
# current date and timenow = datetime.now()# format time in HH:MM:SStime = now.strftime("%H:%M:%S")print("Time:", time)# format datedate_time = now.strftime("%m/%d/%Y, %H:%M:%S")print("Date and Time:",date_time)
While working with data, it is very common to deal with timestamps. Maybe you want to store your data in Unix timestamp format. We will use datetime’s timestamp() function to do that .
# get current datenow = datetime.now()# convert current date into timestamptimestamp = datetime.timestamp(now)print("Date and Time :", now)print("Timestamp:", timestamp)
Similarly, from a timestamp we can covert to date and time objects.
timestamp = 1577971124.673931#convert timestamp to datetime objectdate_obj = datetime.fromtimestamp(timestamp)print("Today's date & time:", date_obj)
Pandas is kind of the main ingredient for data science projects in python and that is rightfully so. It makes dealing with date and time easier than any other methods.
It is a lot easier to convert date and time text strings into pandas Datetime objects using to_datetime().
This function is quite good at converting strings to Python datetime objects by detecting their formats automatically, without needing us to define it using strftime patterns.
# import pandas moduleimport pandas as pd# create date object using to_datetime() functiondate = pd.to_datetime("2nd of jan, 2020")print(date)
There are also a lot of operations that can be done using pandas with date and time datas. But that requires another post of its own. However, I hope this post provides initial concepts about the operations we can do with datetime module and pandas. All the codes used here can be found on my GitHub account https://github.com/muniah .
Originally published at https://muniah.com on January 2, 2020.