Working With Dates & Times
Datetime
Python has a built-in datetime module which provides convenient objects to work with dates and times.
Code
PYTHON
Datetime classes
Commonly used classes in the datetime module are:
- date class
- time class
- datetime class
- timedelta class
Working with 'date' class
Representing Date
A date object can be used to represent any valid date (year, month and day).
Code
PYTHON
Output
Date Object
Code
PYTHON
Output
Today’s Date
Class method
today()
returns a date object with today’s date.Code
PYTHON
Output
Attributes of Date Object
Code
PYTHON
Output
Working with ‘time’ Class
Representing Time
A time object can be used to represent any valid time (hours, minutes and seconds).
Code
PYTHON
Output
Attributes of Time Object
Code
PYTHON
Output
Working with ‘datetime’ Class
Datetime
The datetime class represents a valid date and time together.
Example - 1
Code
PYTHON
Output
Example - 2 It gives the current date and time
Code
PYTHON
Output
DateTime object
Code
PYTHON
Output
Formatting Datetime
The datetime classes have
strftime(format)
method to format the datetime into any required format like - mm/dd/yyyy
dd-mm-yyyy
Format Specifier Meaning Example %y Year without century as a zero-padded decimal number 19, 20, ... %Y Year with century as a decimal number 2019, 2020, ... %b Month as abbreviated name Jan, Feb, ... %B Month as full name January, February %m Month as a zero-padded decimal number 01, 02, …, 12 %d Day of the month as a zero-padded decimal number 01, 02, …, 31 %a Weekday as abbreviated name Sun, Mon, ... %A Weekday as full name Sunday, Monday, ... %H Hour (24-hour clock) as a zero-padded decimal number 00, 01, …, 23 %I Hour (12-hour clock) as a zero-padded decimal number 01, 02, …, 12 %p AM or PM AM, PM %M Minute as a zero-padded decimal number 00, 01, …, 59 %S Second as a zero-padded decimal number 00, 01, …, 59
Code
PYTHON
Output
Parsing Datetime
The class method
strptime()
creates a datetime object from a given string representing date and time.Code
PYTHON
Output
Working with ‘timedelta’ Class
Timedelta object represents duration.
Example 1
Code
PYTHON
Output
Example 2
Code
PYTHON
Output
Calculating Time Difference
Code
PYTHON