Dealing with time data in python

ways to manage time data

·

3 min read

While dealing with data, we often come across data that contains datetime. It is necessary to keep the datetime date in proper format (datetime type), as many times the datetime fields in the dataset are in string format or in integer format. We are going to see how to deal with datetime fields like how to convert them form string to datetime object, or from datetime to string, how to do basic arithmetic on datetime variables and lastly, we see the standard formats.

Firstly you need to import datetime library/module into your code.The datetime module supplies classes for manipulating dates and times in both simple and complex ways.

There are 5 datetypes available in datetime library. datetime.date, datetime.time, datetime.timedelta, datetime.datetime and datetime.tzinfo In this article we are focusing on datetime.datetime. You should include the below import line at the start of your code.

from datetime import datetime

Type Casting datetime

In order to convert a string that contains datetime data into an actual datetime object we can use strptime() method, which creates a datetime object from a given string (representing date and time). However, the datetime attributes should be in a format that datetime can understand.

Printing Datetime

The datetime object has a method for formatting date objects into readable strings. The strftime() method takes one parameter, format, to specify the format of the returned string. check out examples

Arithmetic

You can add or subtract some time from a particular date to get your desired date. Suppose if you want to calculate when the subscription end once started on a specific date. You can add 30 days to that date to get the date when the subscription is going to end. Example date_obj - timedelta(days = 1) subtracts 1 day from date_obj . For more info.

from datetime import timedelta

Common Formats datetime data is available in

  1. ISO Calender

  2. ISO Format

  3. Ordinal

  4. Timestamp

Extracting attributes of datetime

You can extract any component of datetime info like what year it is, what weekday, what month is the date on and so on. For example dt.year gives year, dt.month gives month

Format codes supported by datetime module

DirectiveMeaningRange/ValuesExample
%aWeekdayshort versionWed
%AWeekdayfull versionWednesday
%dDay of month01-3131
%bMonth nameshort versionDec
%BMonth namefull versionDecember
%mMonth number01-1212
%yYearshort version18
%YYearfull version2018
%HHour00-2317
%IHour00-1205
%pAM/PMAM, PMPM
%MMinute00-5958
%SSecond00-5912

Did you find this article valuable?

Support Dataset Stories by becoming a sponsor. Any amount is appreciated!