The datetime Module
Reference:
The datetime
module provides capabilities for handling dates and times. See the "Date Parsing" section below for some ways we can create official datetime objects, and the "Date Formatting" section for some ways to format or display these objects.
NOTE: the difference between a
datetime.date
object and adatetime.datetime
object is that only the latter has information about hours, minutes, and seconds.
Date Parsing
We can create our own date or datetime objects by passing in some hard-coded info (not the most common):
Alternatively, we can reference some built-in methods to get objects representing the current date and/or time:
Alternatively, we can convert a datetime-like string to an official datetime object, either by specifying the string's date format template to the .strptime()
method, or by using a separate parsing method provided by the dateutil
module:
Date Formnatting
Unlike strings, these date and datetime objects are aware of their own datetime-related properties (like year or day of week):
And we can customize the formatting of any date or datetime object by passing a format code to the strftime()
method:
NOTE: here is the list of official "format codes" we can use in conjunction with the
.strptime()
andstrftime()
methods.
Last updated