Create a timezone object for UTC

Introduction

When working with dates and times in Python, you will often need to convert between string representations of dates and Python‘s datetime objects. Being able to flexibly parse strings into datetime objects and format datetime objects into strings is a crucial skill for many Python applications.

In this post, we‘ll take an in-depth look at how to handle converting between strings and datetime objects in Python. We‘ll cover the different ways dates can be represented as strings, how to use Python‘s built-in datetime module to parse and format datetimes, how to handle timezones, and some best practices to keep in mind. Let‘s get started!

Representing Dates as Strings

Before we dive into parsing strings into datetime objects, let‘s discuss the different ways dates and times are commonly represented as strings.

One of the most common and standard ways to represent a datetime as a string is using the ISO 8601 format. ISO 8601 strings look like this:

2023-04-22T10:30:45Z

The different parts are:

  • Date in YYYY-MM-DD format
  • The letter "T" separator
  • Time in HH:MM:SS format
  • Optional fractional seconds
  • Optional timezone (Z means UTC, or an offset like +02:00)

Parsing an ISO 8601 formatted string is well supported by Python‘s datetime classes as we‘ll see later.

Another common way to represent dates as strings is using custom formats like:

Apr 22, 2023

This format has the abbreviated month name, 2-digit day, and 4-digit year separated by spaces and a comma. Parsing strings in custom formats like this takes a bit more work in Python.

Parsing Strings into DateTime Objects

Now that we‘ve seen how dates and times are represented as strings, let‘s look at parsing those strings into Python datetime objects.

Using strptime()

The built-in way to parse a string into a datetime object is using the datetime.strptime() class method. strptime() takes two arguments:

  1. The string to parse
  2. A format string that specifies what each part of the string means

Here‘s a simple example:

from datetime import datetime

date_string = ‘2023-04-22 10:30:45‘ format = ‘%Y-%m-%d %H:%M:%S‘

date_obj = datetime.strptime(date_string, format) print(date_obj) # 2023-04-22 10:30:45 print(type(date_obj)) # <class ‘datetime.datetime‘>

The format string uses special %-codes that map to parts of the date:

  • %Y – 4 digit year
  • %m – 2 digit month
  • %d – 2 digit day
  • %H – 2 digit hour (24-hour)
  • %M – 2 digit minute
  • %S – 2 digit second

Also supports many other codes for parsing different parts of a string into a datetime.

If the string doesn‘t match the format, a ValueError is raised:

from datetime import datetime

date_string = ‘Apr 22, 2023‘ format = ‘%Y-%m-%d‘

date_obj = datetime.strptime(date_string, format) # ValueError

Parsing Timezones

By default, datetime.strptime() creates naive datetime objects that are not timezone aware. If your date strings include timezone information, you need to handle that explicitly.

The %z format code parses timezone information in the form +HHMM or -HHMM:

from datetime import datetime

date_string = ‘2023-04-22T10:30:45+0200‘
format = ‘%Y-%m-%dT%H:%M:%S%z‘

date_obj = datetime.strptime(date_string, format)
print(date_obj) # 2023-04-22 10:30:45+02:00

This creates a timezone-aware datetime object. The timezone information is represented by a datetime.timezone object.

To parse other timezone formats like abbreviations (e.g. ‘EST‘, ‘PDT‘) or the ‘Z‘ UTC designator, you can use the third-party pytz module:

from datetime import datetime
import pytz

date_string = ‘2023-04-22T10:30:45Z‘ format = ‘%Y-%m-%dT%H:%M:%S%Z‘

utc = pytz.timezone(‘UTC‘)

date_obj = datetime.strptime(date_string, format).replace(tzinfo=utc)

print(date_obj) # 2023-04-22 10:30:45+00:00

Here we create a pytz timezone object for UTC and pass that to strptime(). This attaches the UTC timezone to the resulting datetime object.

Flexible Parsing with dateutil

For more flexible parsing of strings in many different formats, you can use the third-party dateutil module. dateutil provides a parse() function that can handle most common date and time formats without needing an explicit format string.

from dateutil.parser import parse

date_string = ‘Apr 22, 2023 10:30:45 AM‘

date_obj = parse(date_string) print(date_obj) # 2023-04-22 10:30:45

dateutil parse() can also handle timezone-aware strings:

  
from dateutil.parser import parse

date_string = ‘Apr 22, 2023 10:30:45 AM EDT‘

date_obj = parse(date_string)
print(date_obj) # 2023-04-22 10:30:45-04:00

For most flexible parsing, dateutil should be your first choice. But if you need more control over exactly how strings are parsed, strptime() is the way to go.

Formatting DateTime Objects into Strings

Converting datetime objects into strings is done using the datetime.strftime() method. strftime() takes a format string argument just like strptime():

from datetime import datetime

now = datetime.now()

print(now.strftime(‘%Y-%m-%d‘)) # ‘2023-04-22‘
print(now.strftime(‘%b %d, %Y‘)) # ‘Apr 22, 2023‘ print(now.strftime(‘%Y-%m-%d %H:%M:%S‘)) # ‘2023-04-22 15:30:45‘

You can use the same %-codes in strftime() as you use in strptime() to control how the resulting string is formatted.

If your datetime object is timezone-aware, the %Z and %z codes can output the timezone:

import pytz  
from datetime import datetime

now = datetime.now(pytz.timezone(‘US/Eastern‘))

print(now.strftime(‘%Y-%m-%d %H:%M:%S %Z‘)) # ‘2023-04-22 11:30:45 EDT‘ print(now.strftime(‘%Y-%m-%d %H:%M:%S %z‘)) # ‘2023-04-22 11:30:45 -0400‘

Best Practices for Working with DateTime Objects

Here are a few tips to keep in mind when working with datetime objects and timezones in Python:

  1. Always use UTC for internal datetime storage and arithmetic. Convert to local timezones only when needed for display.

  2. Be careful when comparing naive and aware datetime objects. You should generally only compare aware datetimes to avoid errors and ambiguity.

  3. When parsing strings, use dateutil if possible for maximum flexibility. Otherwise, use strptime() and pass an explicit format string.

  4. Remember that a datetime object doesn‘t have a format – the format is only applied when converting to/from a string.

Conclusion

In this post we took an in-depth look at parsing strings into Python datetime objects and formatting datetime objects into strings.

We saw how to use strptime() to parse a string given an explicit format, how to handle parsing timezone-aware strings, and how the third-party dateutil module provides a flexible way to parse many common string formats.

We also looked at using strftime() to format a datetime object into a string, including outputting timezones.

Finally, we went over some best practices to keep in mind when working with datetimes and timezones in Python.

I hope this post has been a helpful and comprehensive guide to datetime string conversion in Python. Let me know if you have any other questions!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Similar Posts