Basic DateTime Operations in Python

Munia Humaira
Towards Data Science
7 min readJan 2, 2020

--

Photo by Brooke Lark on Unsplash

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 -

  1. datetime.date : It allows us to manipulate date without interfering time (month, day, year)
  2. datetime.time : It allows us to manipulate date without interfering date (hour, minute, second, microsecond)
  3. datetime.datetime : It allows us to manipulate the combination of date and time (month, day, year, hour, second, microsecond).
  4. 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.
  5. datetime.timedelta : It is the difference between two date, time or datetime instances; the resolution ca

Creating DateTime Objects

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 module
from datetime import datetime

# get today's date
today = 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 datetime
print('Hour: ', dt_nw.hour)

# to get minute from datetime
print('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 module
import calendar

my_date= datetime.now()
# To get month from date
print('Month: ', my_date.month)

# To get month from year
print('Year: ', my_date.year)

# To get day of the month
print('Day of Month:', my_date.day)

# to get name of day(in number) from date
print('Day of Week (number): ', my_date.weekday())

# to get name of day from date
print('Day of Week (name): ', calendar.day_name[my_date.weekday()])

Dealing With Timezones

Now we need to understand two kinds of datetime objects ;

  1. 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.
  2. 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 module
from pytz import timezone

# Create timezone UTC
utc = timezone('UTC')

# Localize date & time
loc = utc.localize(datetime(2020, 1, 1, 3, 50, 0))
print(loc)

# Convert localized date & time into Asia/Dhaka timezone
dhaka = timezone("Asia/Dhaka")
print(loc.astimezone(dhaka))

# Convert localized date & time into Europe/Berlin timezone
berlin = 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.

Timespan and Time Differences

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 timedelta
from datetime import timedelta
print(timedelta(days= 365, hours= 12, minutes= 30))
# get current time
now = datetime.now()
print ("Today's date & time: ", str(now))

#add 365 days to current date
future_date_after_one_year = now + timedelta(days = 365)
print('Date & time after one year: ', future_date_after_one_year)

#subtract 7 days from current date
seven_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.

strftime() & strptime() : Date Formatting

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 datetime
from datetime import datetime

date_str = "2 january, 2020"

# format date
date_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 time
now = datetime.now()

# format time in HH:MM:SS
time = now.strftime("%H:%M:%S")
print("Time:", time)

# format date
date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print("Date and Time:",date_time)

Dealing With Timestamp

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 date
now = datetime.now()

# convert current date into timestamp
timestamp = 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 object
date_obj = datetime.fromtimestamp(timestamp)

print("Today's date & time:", date_obj)

Pandas DateTime Objects

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 module
import pandas as pd

# create date object using to_datetime() function
date = 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.

--

--