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
ISO Calender
ISO Format
Ordinal
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
Directive | Meaning | Range/Values | Example |
%a | Weekday | short version | Wed |
%A | Weekday | full version | Wednesday |
%d | Day of month | 01-31 | 31 |
%b | Month name | short version | Dec |
%B | Month name | full version | December |
%m | Month number | 01-12 | 12 |
%y | Year | short version | 18 |
%Y | Year | full version | 2018 |
%H | Hour | 00-23 | 17 |
%I | Hour | 00-12 | 05 |
%p | AM/PM | AM, PM | PM |
%M | Minute | 00-59 | 58 |
%S | Second | 00-59 | 12 |