In this series, you will learn how to use a date and time in Python. Dealing with dates and times can be complicated, but fortunately, we have many open-source libraries available in Python to work with it.
Date and Time Series
This Python Date and Time Series contains the following in-depth tutorial. You can directly read those.
- Get Current Date and Time in Python: You'll learn to get the current date and time in Python using the datetime and time module.
- Python DateTime Format Using Strftime(): You'll learn to represent date and time in various formats in Python using the
strftime()function of a datetime module and time module. For example, represent a date numerically in format, like “17-06-2021“ or textual string format like “Tuesday, 23 June 2021.”
- Python String to DateTime using strptime(): You'll learn to parse a string representing a date or time to a datetime using the
strptime()with the various standard date formatting codes available in Python
- Timestamp In Python: You'll learn to work with timestamp. Convert datetime to timestamp and vice-versa. Format timestamp to string object and vice-versa
- TimeDelta in Python: You'll learn to calculate the difference between two datetime using timedelta. How to use the
timedeltaclass to calculate future dates and past dates.
- Working With TimeZones in Python: You'll learn the handling of timezone by creating a timezone-aware date and time. Get the current time in a different time zone. Get timezone name, UTC offset, and DST offset if DST is in effect and perform timezone conversion
The below list contains the solution to the common questions and challenges you can face working with datetime in Python.
- Python Difference Between Two Dates in Days
- Python Difference Between Two Dates in Months and Years
- Calculate Time Difference in Python
- Python Get the Day of the Week
- Python Get Business Days
- Python Measure the Execution Time of a Program
- Python Get ISO 8601 Datetime
- Python Datetime to Seconds
- Python Convert Seconds To hh:mm:ss (Hours, Minutes, and Seconds)
- Python Get File Creation and Modification DateTime
Below is the list of standard libraries we can use to work with date and time.
- datetime: The datetime is a built-in module that provides functions to handle many complex functionalities involving the date and time. It has a date, time, timezone, and timedelta classes to work with date and time.
- calendar: In Python, a calendar is a built-in module to work with calendar-related activities and operations. In the calendar module, by default, Monday is the first day of the week, and Sunday is the last day of the week as per the Gregorian calendar.
- time: time module provides a different function to work with time-related activities where dates are not needed.
Get Current Date and Time in Python
datetime module using the import statement like
import datetime and you are good to go.
The datetime module has a
datetime class that contains the current local date and time. Use the
now() method to access the current date and time.
from datetime import datetime # get current date and time now = datetime.now() print(now) # print class print(type(now))
2021-06-04 10:24:04.646972 <class 'datetime.datetime'>
As you can see in the output we got the current date and time in the following format.
Read More: How to get Current Date and Time in Python to learn various other ways to get the current datetime, local time, UTC time, GMT time, and ISO time. Also, learn to get the current time in the specific timezone.
Classes In The Datetime Module
Python provides the
dir() function to list all attributes and functions of a module. Let's see the constants and classes of a datetime module.
import datetime print(dir(datetime))
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo']
Each class has various methods to access and manipulate dates and times. We'll learn each one by one.
- date Class
- time Class
- datetime Class
- timedelta Class
Date Class in DateTime
We can represent the date object using the
date class and the date class initializes the native date. It always considers the Gregorian calendar.
The constructor of the
date class takes three parameters which include year, month, and day.
Syntax to create a date object:
datetime.date(year, month, day)
The arguments should be in the following range :
MINYEAR <= year <= MAXYEAR
1 <= month <= 12
1 <= day <= number of days in the given month and year
If we pass an argument outside of given ranges,
ValueError is raised.
Example: Create a date object in Python.
from datetime import date date1 = date(2021, 2, 10) print("Date is :", date1)
Date is : 2021-02-10
Get Today's Date
date.today() function returns the current local date.
from datetime import date # Get today's date today = date.today() print('Today:', today) # extract attributes print("Year:", today.year) print("Month:", today.month) print("Day:", today.day)
Today: 2021-07-16 Year: 2021 Month: 7 Day: 16
As you know, the datetime object contains both date and time. To work only with time, we can use the
time class from the datetime module.
To represent the local time, we can instantiate the
time object from the
time class. The arguments for
time class are optional.
Syntax to create a time object:
datetime.time(hour, minute, second, microsecond, tzinfo, *, fold)
The arguments should be in the following range:
0 <= hour < 24,
0 <= minute < 60
0 <= second < 60
0 <= microsecond < 1000000
fold in [0, 1]
tzinfois the timezone information.
If we pass an argument outside of given ranges,
ValueError is raised.
from datetime import datetime from datetime import time # Extract time from datetime object now = datetime.now() print("Current time is:", now.time()) # Create empty time object t = time() print('Time', t) # create time object with attribute names t1 = time(hour=7, minute=10, second=34) print("time is:", t1) # time without attributes names t2 = time(7, 10, 45) print("time is:", t2) # time with microseconds t3 = time(7, 10, 45, 400437) print("time is:", t3)
Current time is: 12:23:20.308263 Time 00:00:00 time is: 07:10:34 time is: 07:10:45 time is: 07:10:45.400437
Extract Hours, Minutes, Second from Time Object
The time class provides the following attributes to access the induvial component such as a hours, minutes, seconds, microseconds from a
from datetime import datetime # Extract time from datetime object t = datetime.now().time() print('Time is:', t) print('Hours', t.hour) print('Minutes', t.minute) print('Seconds', t.second) print('Microseconds', t.microsecond)
Time is: 12:32:24.208371 Hours 12 Minutes 32 Seconds 24 Microseconds 208371
datetime class contains information about both date and time. It Assumes the Gregorian Calendar and there are 360*24 seconds every day.
Create datetime object
datetime.datetime(year, month, day, hour, minute=0, second, microsecond, tzinfo=None)
Arguments must be integers in the following ranges:
MINYEAR <= year <= MAXYEAR,
1 <= month <= 12,
1 <= day <= number of days in the given month and year,
0 <= hour < 24,
0 <= minute < 60,
0 <= second < 60,
0 <= microsecond < 1000000,
fold in [0, 1].
If we pass an argument outside of given ranges,
ValueError is raised.
Example: Create a
# import datetime class from datetime import datetime # Get current date and time now = datetime.now() print('Current datetime:', now) # create datetime object dt = datetime(year=2021, month=2, day=17, hour=13, minute=47, second=34) print("Datetime is:", dt)
Current datetime: 2021-07-16 12:35:58.497313 Datetime is: 2021-02-17 13:47:34
Get Date, Time, TimeStamp from Datetime
The datetime module provides several attributes and functions to access the induvial component such as a date, time, timestmap, year, month, day, hour, minute, seconds.
from datetime import datetime # create datetime object dt = datetime.now() print("Datetime is:", dt) # Get date, time, and timestamp print('Date:', dt.date()) print('Time:', dt.time()) print('Timestamp:', dt.timestamp()) # Get Attributes print('Year:', dt.year) print('Month:', dt.month) print('Day:', dt.day) print('Hours:', dt.hour) print('Minutes:', dt.minute) print('Seconds:', dt.second) print('Microseconds:', dt.microsecond)
Datetime is: 2021-07-16 12:43:14.701186 Date: 2021-07-16 Time: 12:43:14.701186 Timestamp: 1626419594.701186 Year: 2021 Month: 7 Day: 16 Hours: 12 Minutes: 43 Seconds: 14 Microseconds: 701186
Create DateTime from Timestmap
We can convert the timestamp back to
datetime object using the
fromtimestamp() method that is available in the both
It returns the local date and time corresponding to the POSIX timestamp.
from datetime import datetime # timestamp ts = 1617295943.17321 # convert to datetime dt = datetime.fromtimestamp(ts) print("The date and time is:", dt) # output 2021-04-01 22:22:23.173210
Read More: Working with Timestamp in Python
Python DateTime Formatting
DateTime to String
We can represent date and time into various formats in Python using the
strftime() function of a datetime module and time module.
strftime() method returns a string representing of a
datetime object according to the format codes.
Example: Convert a datetime to the string format of
from datetime import datetime # current dateTime now = datetime.now() # convert to string date_time_str = now.strftime("%d/%m/%Y %H:%M:%S") print('DateTime String:', date_time_str) # output 23/06/2021 08:44:18
Read More: Python DateTime Format Using Strftime()
String to DateTime
We can parse a string to a datetime object using the
strptime() with the various standard date formatting codes available in Python.
Example: Convert String to Datetime
Let us see with an example where we have a string representing the date and time in the standard format (
from datetime import datetime # Date String in dd/mm/yyyy HH:MM:SS format dt_string = "12/06/2021 09:15:32" # Convert string to datetime object dt_object = datetime.strptime(dt_string, "%d/%m/%Y %H:%M:%S") print(dt_object) # Output 2021-06-12 09:15:32
Read More: Python String to DateTime using strptime()
TimeDelta: Differance Between Two DateTime
A timedelta represents a duration which is the difference between two dates, time, or datetime instances, to the microsecond resolution.
Using the datetime moduel's
timedelta class we can add or subtract weeks, days, hours, minutes, seconds, microseconds, and milliseconds from a given date and time.
Also, we can calculate the difference between two datetime.
from datetime import datetime # given datetime current_date = datetime.now() x_date_time = datetime(year=2020, month=3, day=21, hour=12, minute=30) # Difference between two dates # Get timedelta timedelta = current_date - x_date_time print('Differance:', timedelta) print(type(timedelta))
Differance: 469 days, 20:39:07.830124 <class 'datetime.timedelta'>
Read More: TimeDelta in Python.
Handling TimeZone in Python
A time zone represents the standardized time depending on which part of the world is being considered.
The pytz library has implemented a timezone class for handling arbitrary fixed offsets from UTC and timezones.
In Python, a date object can be mentioned with or without timezones. Based on that, an object is known as Naive or Aware. A date object, by default, is naive. A datetime or time object is aware if it holds the timezone(tz) value.
Example: Create a timezone-aware datetime in Python.
from datetime import datetime import pytz # current Datetime unaware = datetime.now() print('Timezone naive:', unaware) # US/Central timezone datetime aware_us_central = datetime.now(pytz.timezone('US/Central')) print('US Central DateTime', aware_us_central)
Timezone naive: 2021-07-09 13:22:02.256978 US Central DateTime 2021-07-09 02:52:02.313026-05:00
Python Time module
Python time module provides various functions to perform time-related activities. Following are the most commonly used functions of the time module.
||Return the time in seconds since the epoch as a floating point number|
||Suspend execution of the calling thread for the given number of seconds|
||Convert a time expressed in seconds since the epoch to a string of a form: 'Sun Jun 20 23:21:05 2021' representing local time|
||Convert a time expressed in seconds since the epoch to a local time in the a
||It returns the time in seconds that has lapsed/passed since the epoch. This is the inverse function of
||Convert a time expressed in seconds since the epoch to a
||Convert a string representing the time according to a format. Return value is The return value is a
||Convert a tuple or
||Accepts a time-tuple and returns a readable 24-character string such as 'Tue Dec 11 18:07:14 2008'.|
import time seconds = time.time() print("Current time in seconds:", seconds) local_time = time.localtime(seconds) print('Local Time', local_time) # time in string form print('Time in String:', time.ctime(seconds)) # Formatting the time to display in string format print('Formatted Time:', time.strftime("%d/%m/%Y %H:%M:%S", local_time)) # String to Time Object print('Time object:', time.strptime("16/07/2021 17:33:37", "%d/%m/%Y %H:%M:%S"))
Current time in seconds: 1626437772.1504333 Local Time time.struct_time(tm_year=2021, tm_mon=7, tm_mday=16, tm_hour=17, tm_min=46, tm_sec=12, tm_wday=4, tm_yday=197, tm_isdst=0) Time in String: Fri Jul 16 17:46:12 2021 Formatted Time: 16/07/2021 17:46:12 Time object: time.struct_time(tm_year=2021, tm_mon=7, tm_mday=16, tm_hour=17, tm_min=33, tm_sec=37, tm_wday=4, tm_yday=197, tm_isdst=-1)
Python Calender Module
Python has a built-in module called calendar for calendar-related activities. This module supplies calendar-related functions, including functions to print a text calendar for a given month or year.
By default, the calendar takes Monday as the first day of the week and Sunday as the last one. We can also change this for that we can use
calendar.setfirstweekday() function. To use the calendar first, we need to Import it.
The below table shows the list of functions available with the calendar module.
||Returns the current setting for the weekday that starts each week. By default, when the calendar is first imported, this is 0, meaning Monday.|
||Returns True if the year is a leap year; otherwise, False.|
||Returns the total number of leap days in the years within range(y1,y2).|
||Returns a multiline string with a calendar for month of the year, w is the width in characters of each date. l is the number of lines for each week.|
||Returns a list of lists. Each sublist denotes a week.|
||It returns two integers. The first one is the code of the weekday for the first day of the month in year and second is the number of days in the month. Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 to 12|
||it returns sets the first day of each week to a weekday. Weekday codes are 0 (Monday) to 6 (Sunday)|
||It accepts a time instant in time-tuple form and returns the same instant as a floating-point number of seconds|
||It returns the weekday code for the given date. Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 (January) to 12 (December).|
import calendar year = 2021 month = 6 # Display calendar print(calendar.month(year, month))
June 2021 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
All Date and Time Tutorials