Python offers the datetime library for handling many date-based operations such as converting timestamps into human-readable formats. This library provides convenient means to convert string timestamps to datetime objects via which developers are provided a unified API for interacting with, updating and making time-based calculations.
In many cases, string-formatted timestamps need to be converted to datetime objects. This allows easy manipulation, comparison, and standardization across an application. Also, one also finds the case to convert datetime objects to a string in Python as well — perhaps to provide human-readable outputs. In this short tutorial, both cases will be addressed and considered.
Converting from a datetime object to a string is as simple as specifying the output format and using the
# Create a datetime object dto = datetime.now() # Convert to string print(dto.strftime("%Y-%m-%d")) # Output 2022-06-17
One can also easily convert from string to datetime in Python using the
strptime function as such:
# Have a string dto = "2022-06-17" # Convert to datetime dto = datetime.strptime(dto, "%Y-%m-%d") >>> dto 2022-06-17 >>> type(dto) <class 'datetime.datetime'>
Introduction: Datetime & Time Utilities
Handling dates, times, and calendar events in programming languages are deceptively complex. One must account for timezones, daylight savings changes, and even leap years. Fortunately for developers, Python offers the datetime module as part of the standard library.
Datetime objects can be categorized as either aware or naive. An “aware”
datetime object contains information about daylight savings time and the intended timezone. As such, these objects can be compared relative to one another without issue or need for conversion.
datetime object only contains information about the time (which can include year, day, month as well) but no information about timezones or daylight savings periods. As such, application developers must decide how these objects are to be compared.
Python’s datetime module converts between strings and datetime objects using a unique symbolic syntax. These symbols can be passed in string format to the datetime module via the
strptime functions and control the format in which a datetime object is either parsed from a string or converted to a string.
strftime method creates a string from a datetime object and is used as such:
# Create a datetime object dto = datetime.now() # Convert to string dto_string = dto.strftime("%Y-%m-%d") >>> dto_string 2022-06-17 <class 'str'> >>> dto 2022-06-17 00:00:00 <class 'datetime.datetime'>
Note that the
dto object remains a
datetime object, meaning the
strftime the method returns a string object but does not affect the underlying object. The meaning of this function’s name isn’t certain but possibly “string format time.”
strptime method creates a new
datetime object from a string object and is used as such:
# Have a string dto = "2022-06-17" # Convert to datetime dto = datetime.strptime(dto, "%Y-%m-%d") >>> dto 2022-06-17 00:00:00 >>> type(dto) <class 'datetime.datetime'>
Note that the
dto object now contains information for the hours, minutes, and seconds even those this information was not supplied. This utility will assume midnight exactly unless otherwise specified. The meaning of this function isn’t certain either, but possibly “string parse time.”
Formatting datetime objects and strings resulting form the
strftime function require some working knowledge of the datetime format codes. Python uses C-standard (1989) syntax for string formatting. See the full reference here. Below are some of the more commonly-used terms:
|%Y||Year with century as a decimal number.||2001|
|%y||Year without century as a zero-padded decimal number.||01|
|%m||Month as a zero-padded decimal number.||03|
|%B||Month as locale’s full name.||January|
|%b||Month as locale’s abbreviated name.||Jan|
|%a||Weekday as locale’s abbreviated name.||Mon|
|%A||Weekday as locale’s full name.||Monday|
|%H||24-Hour as a zero-padded number.||22|
|%I||12-Hour as a zero-padded number||12|
|%M||Minute as a zero-padded decimal number||03|
|%S||Second as a zero-padded decimal number.||59|
|%Z||Time zone name||UTC|
See the full reference here.
Convert String to Datetime
The above references and general use of the
strptime method provides the groundwork for converting strings to datetime objects in Python. The essential steps of this process are as follows:
- Decide on the format
- Construct Format string based on the reference list
- Pass string and format string to
Below is a slightly more complex example in which a string containing date, time and timezone information is presented:
""" Convert a string to a datetime object """ from datetime import datetime # Create a string datetime date = "2022-06-17T18:23:59" # Print output print(date, type(date))
Here we define an ISO format string representing the date and time then use the
strptime method to convert it to a datetime object. The following is the result from running this code:
2022-06-17 18:23:59 <class 'datetime.datetime'>
Convert Datetime to String
Using Python to convert a datetime object to a string is similar to the process of converting a string to a datetime object — our previous example. One must use the same formatting syntax, make the same accommodations for timezone handling, and use the same underlying
datetime class. The difference is in the use of the
strftime methods rather than the
strptime. Consider the code below:
""" Convert datetime object to a string """ from datetime import datetime, timezone # Create a datetime object using explicit arguments date = datetime( year=2022, month=6, day=17, hour=18, minute=23, second=59, tzinfo=timezone.utc ) print(date, type(date)) # Convert to string using formatting syntax date = date.strftime("%Y-%m-%dT%H:%M:%S %Z%z") print(date, type(date))
In this code a datetime object is constructed explicitly using keyword arguments, including the timezone — thus making an aware datetime object. This object is then converted to a string representation via the
strftime method such that the full date, time, and timezone information is displayed. Below is the resulting output:
2022-06-17 18:23:59+00:00 <class 'datetime.datetime'> 2022-06-17T18:23:59 UTC+0000 <class 'str'>
Handling Timezone Information
In the first example, a string was converted to a naive datetime object — meaning there is no timezone information. The following code outlines a process via which timezone information (be it local timezone or another) can be injected into any datetime object:
""" Convert a string to a datetime object, adding timezone information, then convert back into a string with timezone information. """ from datetime import datetime, timezone # Create a string datetime date = "2022-06-17T18:23:59" # Convert to naive datetime object date = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S") # Add UTC Timezone Info date.replace(tzinfo=timezone.utc) print("Initial Timezone:", date.tzinfo) # Add UTC Timezone w/ Assignment date = date.replace(tzinfo=timezone.utc) print("Updated Timezone:", date.tzinfo) # Convert to Timezone Format tz_date = date.strftime("%Y-%m-%dT%H:%M:%S %Z%z") print("Converted Timezone:", tz_date)
Here a datetime object is created via the
strptime method which parses the
date string which provides no timezone information. The
replace method is then used to replace the
None value for the
tzinfo field with the
timezone.utc value indicating UTC time. However, in printing the value for
date directly afterward, it is realized that the
date object is still timezone naive — what gives?
To ensure the replacement happens one must assign the return value to a new variable or, as is the case with this example, replace the value of an existing variable. After such an approach in the above code, we now see the
date.tzinfo field to reflect the intended value.
Finally, we use the
strptime method to convert the now-aware
date object into a final output string which reflects the timezone information via the
%T%t format syntax. The result of this code is as follows:
Initial Timezone: None Updated Timezone: UTC Converted Timezone: 2022-06-17T18:23:59 UTC+0000
The datetime module in Python allows developers to easily convert between strings and datetime objects. Special attention should be given to ensuring timezone information is encoded, replaced, and converted to a string format as intended. These values, while tricky to manage sometimes, allow the robust representation of dates and times through a range of applications.