Python Date and time Module
There is a Python module that is comprised of various functions to deal, manipulate, and work with dates and date objects. This module is known as the Python datetime module. We can simply start working with dates by importing this module and using the functions and classes it provides.
Current Date and Time with Datetime in Python
Let us see how with the help of the Python datetime module and a simple line of code we can get the current date in Python.
Python Datetime Example:
#import datetime python
import datetime
a = datetime.datetime.now()
print(a)
When the above code block is executed, it will display the current date (containing year, month, day, hour, minute, second, and microsecond in the same order). In the ‘datetime.datetime’ statement, the first datetime is the module and the second one is the datetime class inside of the datetime method which contains information from both date and time objects.
We can also display just one of the attributes of date in python, such as, just the year.
Example:
import datetime
a = datetime.datetime.now()
print(a.year)
Creating Date Objects in Python
In certain cases, we will want to create a custom date instead of just displaying the current date. In those cases, we can use the datetime() class constructor of the Python datetime module.
This Python datetime() class constructor requires three parameters to create a date, that is, year, month, and day.
Example:
import datetime
a = datetime(2050,11,11)
print(a)
Output:
2050-11-11
The Python datetime() class constructor also takes parameters for time and timezone, which are hour, minute, second, microsecond, and tzone. But these parameters are optionally and rarely used. The default value of these parameters is set to 0.
Get 100% Hike!
Master Most in Demand Skills Now!
The strftime() Method: Convert String to Datetime in Python
The datetime module in Python also has a method to convert the date objects into readable strings. So, we can display the month or day in a readable string format instead of numerical representation.
Example:
import datetime
a = datetime.datetime(2020,6,19)
print(a.strftime(“%d”), a.strftime(“%B”))
Output:
19, June
Now, we might be wondering, how do we specify that we want to display the month in a readable string format and what ‘%B’ and ‘%d’ are. Well, Python uses C style formatting to generate new strings. These are called format codes. There are different format codes for different attributes of the date object.
The following table contains a list of all legal format codes and their short descriptions:
Format code |
Description |
Example |
%a |
Short version of weekday |
Wed |
%A |
Full version of weekday |
Wednesday |
%w |
Weekday as a number starting from 0 to 6, where 0 is Sunday |
3 |
%d |
Day of the month in numerical format starting from 01 to 31 |
15 |
%b |
Short version of month name |
Dec |
%B |
Full version of month name |
December |
%m |
Month as a number starting from 01 to 12 |
12 |
%y |
Short version of a year, i.e., without indicating the century |
19 |
%Y |
Year in full version |
2019 |
%H |
Hour in 24-hour format starting from 00 to 23 |
17 |
%I |
Hour in am-pm format; 00–12 |
05 |
%p |
AM/PM |
PM |
%M |
Minute starting from 00 to 59 |
41 |
%S |
Second starting from 00 to 59 |
08 |
%f |
Microsecond starting from 000000–999999 |
054647 |
%Z |
Timezone |
CST |
%j |
Day of the year in numerical format, starting from 001 to 366 |
365 |
%U |
Week of the year in numerical format, starting from 00 to 53, where Sunday is the first day of the week |
52 |
%W |
Week of the year in numerical format, starting from 00 to 53, where Monday is the first day of the week |
52 |
%c |
Local version of date and time |
Mon Mar 04 17:41:00 2018 |
%x |
Local version of date |
03/04/19 |
%X |
Local version of time |
19:21:00 |
We can use any of these codes with the strf method to display their respective values. The strftime method can take one or more than one format codes as argument, as shown in our example, where we have used ‘%B’ to display the full version of the month name in a readable string format and ‘%d’ to display the day of the month in a numerical format.
The strptime() Method: Convert Datetime to String in Python
The strptime() method creates a datetime object from the given string.This method takes the string to be converted and the format code as arguments. It’s not possible to create a datetime object from every string. The string has to be in a certain format.
from datetime import datetime
date_str = "21 June, 2018"
print("Date String =", date_str)
print("Type of Date String =", type(date_str))
date_object = datetime.strptime(date_str, "%d %B, %Y")
print("date_object =", date_object)
print("type of date_object =", type(date_object))
The output will be
Date String = 21 June, 2018
Type of Date String = <class 'str'>
date_object = 2018-06-21 00:00:00
type of date_object = <class 'datetime.datetime'>
Timestamp to Datetime and vice-versa in Python
A Unix timestamp is the number of seconds between a particular date and January 1, 1970, at UTC.
Python Timestamp to Datetime
Here, we used the datetime.fromtimestamp() classmethod which returns the datetime object. This object is stored in the dt_object variable.
from datetime import datetime
timestamp = 1545730073
dt_object = datetime.fromtimestamp(timestamp)
print("dt_object =", dt_object)
print("type(dt_object) =", type(dt_object))
The output will be
dt_object = 2018-12-25 09:27:53
type(dt_object) = <class 'datetime.datetime'>
Python Datetime to Timestamp
You can get the timestamp from a datetime object using datetime.timestamp() method.
from datetime import datetime
now = datetime.now()
timestamp = datetime.timestamp(now)
print("timestamp =", timestamp)
The output will be the timestamp for the current datetime.
With this, we come to the end of this module in Python Tutorial. Here we have learned about dealing with dates and time in Python with the help of datetime module. Now, if you want to know, how python can be used for data science, you can go through this blog on python data science tutorial.
Further, check out our offers for Python training Courses and also refer to the trending Python coding interview questions prepared by the industry experts.