The datetime
module in the standard library provide essential classes and functions for representing and manipulating dates and time. It shares some functionality with the time module. Both provide ways to access and manipulate date and time values, with the datetime
module offering more advanced features and capabilities.
The module contains several classes for working with dates and time. These classes can be summarized as:
time
: Represents a single time, including hour, minute, second, microsecond , and tzinfo.date
: Represents a single date, including year, month, and day.datetime
: This class combines the features of thedate
andtime
classes into a single class.timedelta
: This class represents the difference between two datetime objects.tzinfo
: This abstract class is used to define time zones and daylight saving time.timezone
: This class is used to create concrete time zone objects.
We will have to import the datetime
module or the specific required assets in our programs before use.
Working with Time - the time class
The datetime
module defines the time
class which represents time values without date information.. In this class, time objects are represented using 5 parameters i.e hour
, minute
, second
, microsecond
and tzinfo
. We can use these attributes to manipulate, display, or compare time values. To instantiate a time object we pass the necessary arguments to the constructor using the following syntax:
time(hour = 0, minute = 0, second = 0, microsecond = 0, tzinfo = None )
All the five arguments are optional, they all default to 0 except the tzinfo
which defaults to None
.
minimum and maximum time values
The time class defines the min
and max
attributes which represent the smallest and largest time values, respectively. The two attributes can be used to determine the valid range of values for time objects.
The replace() method
We can use the replace()
method create a new time object based on the values of the current time . The method takes any of the 5 parameters - hour
, minute
, second
, microsecond
, tzinfo
.
replace(hour = None, minute = None, second = None, microsecond = None, tzinfo = None)
The strftime() method
The strftime()
method allows us to customize the way time is displayed.
strftime(format = "%H:%M:%S")
The format
parameter should be a string with placeholders representing how the time should be formatted. By default, the "%H:%M:%S"
format is used, this is the reason why time is displayed as hh:mm:ss.
The methods of the time class can be summarized as:
Method | Usage |
---|---|
isoformat() |
Returns a string representation of the time in ISO 8601 format. |
strftime() |
Formats the time using the given format string. |
replace() |
Creates a new time object from the current with some values replaced. |
dst() |
Returns 1 if Daylight Saving Time (DST) is in effect, 0 otherwise. Only works if tzinfo is not None . |
utcoffset() |
Returns the local timezone’s offset from UTC. Only works if tzinfo is not None . |
tzname() |
The name of the timezone if tzinfo is not None . |
Working with dates - the date class
The date
class is used to represent calendar dates without time information. A date object is created using the class constructor which takes parameters for year
, month
and date
.
date(year, month, day)
All the three values are required when instantiating date objects.
If you want current date, you can simply use the today()
class method.
We can check the smallest and the largest valid dates using the min
and max
, class attributes.
Date methods
The date class defines some useful methods. We have already seen one of the methods, i.e today()
, other methods includes:
date.replace()
This method creates a new date object based on the values of the current date object.
replace(year = None, month = None, day = None)
date. fromtimestamp()
If you are familiar withe the time module, you might already be familiar with how timestamps work. In a nutshell, a timestamp refers the number of seconds since the epoch(January 1, 1970) up to a certain date.
The fromtimestamp()
method creates a date objects from a given timestamp.
fromtimestamp(timestamp)
date.isoformat()
This method converts a date object into a ISO 8601 formatted string.
date.ctime()
This method is used to format a date object into the "%a %b %d %H:%M:%S %Y" format.
ctime()
The default format is "%a %b %d %H:%M:%S %Y" meaning that, with this method, a date is represented as for example Sunday, July 28th, 11:35:03, 2023.
date.strftime()
This method allows us to customize how a date object will look using custom formats.
strftime(format)
The format is a string containing the relevant placeholders representing how the date should be displayed.
All the methods of the date class are summarized by the following table.
Method |
Usage |
---|---|
ctime() |
Returns a string representing the date in a human readable form. |
fromisocalendar() |
Returns a date corresponding to the ISO calendar |
fromisoformat() |
Returns a date object from the string representation of the date |
fromordinal() |
Returns a date object from the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1 |
fromtimestamp() |
Creates a date object from a given timestamp |
isocalendar() |
Returns a tuple year, week, and weekday |
isoformat() |
Used to represent a date object as a string in ISO 8601 format. |
isoweekday() |
Returns the day of the week as an integer with Monday as 1. |
replace() |
Creates a new date object from the values of the current date replaced with the arguments values. |
strftime() |
Returns a string representation of the date with the given format |
timetuple() |
Converts the current date into time.struct_time object. |
today() |
Returns the current date in local time |
toordinal() |
Return the proleptic Gregorian ordinal of the date. |
weekday() |
Returns the day of the week as integer with Monday as 0. |
Dates and Time combined - The datetime class
The datetime
class is used to hold values consisting of both date and time components.
Note: the class shares the same name with the module.
To instantiate objects of this class, we use the following syntax:
datetime(year, month, day, hour = 0, minute = 0, second = 0, microsecond = 0, tzinfo = None)
The date
arguments are required while the time
arguments are optional as shown in the above syntax.
This class' functionality is simply the combination of the date
and the time
classes. It is actually possible to instantiate a datetime objects from two seperate date and time objects using the combine method.
The current date and time
One of the most used methods of the datetime
classes is the now()
method, this method returns the current local time including date and time components.
Other almost similar to the now()
method are the today()
and the utcnow()
methods. In most cases the three methods usually return the same value. Except that the utcnow()
method returns timezone aware datetime
objects while the other two returns timezone naive datetime
objects.
Formatting and Parsing
By default, the datetime
objects are formatted using ISO 8601 format.(YYYY-MM-DDTHH:MM:SS.), for example 2023-05-19T14:45:53, which represents May 19th, 2020 at 2:45:53 PM. This format allows for the consistent formatting of datetime objects to be displayed and transferred across different systems, as long as they adhere to the standard.
We can change the default format using the various methods meant for this purpose. The most basic of them is the ctime()
, which converts a datetime into a string in the "Month DD YYYY HH:MM:SS"
format.
The strftime()
method allows us to customize the format.
Create a datetime object from a formatted string
If a string contains a valid datetime
values, we can use the strptime()
method to create a datetime
object from the strings.
strptime(datetime_string, format)
Note: The methods of the datetime class and its objects are similar to those of date and time classes combined, with the adjustments done where necessary.