Convert Python String to Datetime with Timezone

Recently, I was working on a project where I had to process log files from multiple servers across different time zones in the USA.

The challenge was that all the timestamps were stored as strings. Some were in EST (Eastern Standard Time), some in PST (Pacific Standard Time), and others in UTC.

At first, I thought this would be simple. But I quickly realized that converting a Python string to a datetime with a timezone requires a few extra steps.

In this tutorial, I’ll show you exactly how I solved this. I’ll cover different methods, from using Python’s built-in datetime module to using external libraries like pytz and dateutil.

Methods to Convert Python String to a Datetime with a Timezone

When working with Python applications, you’ll often receive date and time data as strings. For example:

  • API responses from web services.
  • Log files from servers in different states.
  • User input in online forms.

The problem is that strings are just text. Python can’t perform date arithmetic, comparisons, or scheduling with them.

1 – Use Python’s datetime.strptime

The first method I use is the built-in datetime.strptime function. This is the easiest way when I know the exact format of the string.

Here’s an example where I convert a timestamp string into a datetime object and then add a timezone.

from datetime import datetime, timezone, timedelta

# Example timestamp string (New York time, EST)
timestamp_str = "2025-09-23 14:30:00"

# Step 1: Convert string to datetime (naive datetime, no timezone yet)
dt_naive = datetime.strptime(timestamp_str, "%Y-%m-%d %H:%M:%S")

# Step 2: Attach timezone (EST is UTC-5)
est_timezone = timezone(timedelta(hours=-5))
dt_est = dt_naive.replace(tzinfo=est_timezone)

print("Naive datetime:", dt_naive)
print("Datetime with EST timezone:", dt_est)

You can see the output in the screenshot below.

convert string to datetime python

This method works well when the date string format is fixed. But if the string format changes, I prefer other methods.

2 – Convert String to Datetime with pytz

Another method I use is with the pytz library. This is especially useful when I need to handle US daylight saving time correctly.

Here’s how I do it:

from datetime import datetime
import pytz

# Example timestamp string
timestamp_str = "2025-09-23 14:30:00"

# Step 1: Convert string to naive datetime
dt_naive = datetime.strptime(timestamp_str, "%Y-%m-%d %H:%M:%S")

# Step 2: Localize to a timezone (America/New_York handles DST automatically)
eastern = pytz.timezone("America/New_York")
dt_eastern = eastern.localize(dt_naive)

print("Naive datetime:", dt_naive)
print("Datetime with timezone:", dt_eastern)

You can see the output in the screenshot below.

python string to datetime

The beauty of pytz is that it knows about daylight saving time rules in the USA. For example, if the date falls in March or November, it automatically adjusts the offset.

3 – Convert String to Datetime with dateutil.parser

When I don’t know the exact format of the string, I use the dateutil library. This library is smart enough to parse many different date formats automatically.

Here’s an example:

from dateutil import parser
import pytz

# Example timestamp string with timezone info
timestamp_str = "September 23, 2025 2:30 PM EST"

# Step 1: Parse string directly
dt_parsed = parser.parse(timestamp_str)

# Step 2: Convert to another timezone (e.g., Pacific Time)
pacific = pytz.timezone("America/Los_Angeles")
dt_pacific = dt_parsed.astimezone(pacific)

print("Parsed datetime:", dt_parsed)
print("Converted to Pacific Time:", dt_pacific)

You can see the output in the screenshot below.

string to datetime python

This method is my favorite when dealing with user input or messy log files. I don’t need to specify the format string; it just works.

4 – Convert String to Datetime in UTC

In many Python projects, especially when working with APIs, I prefer to store all datetimes in UTC.

Here’s how I convert a string to UTC:

from datetime import datetime, timezone

# Example timestamp string
timestamp_str = "2025-09-23 14:30:00"

# Step 1: Convert string to naive datetime
dt_naive = datetime.strptime(timestamp_str, "%Y-%m-%d %H:%M:%S")

# Step 2: Attach UTC timezone
dt_utc = dt_naive.replace(tzinfo=timezone.utc)

print("UTC datetime:", dt_utc)

You can see the output in the screenshot below.

python convert string to datetime

Using UTC makes it easier to compare times across servers in different US states without worrying about daylight saving.

5 – Convert String to Datetime from ISO 8601 Format

Many APIs return datetime strings in ISO 8601 format (e.g., “2025-09-23T14:30:00Z”).

Python has built-in support for this format.

from datetime import datetime

# Example ISO 8601 string
timestamp_str = "2025-09-23T14:30:00Z"

# Convert directly using fromisoformat (Python 3.7+)
dt_iso = datetime.fromisoformat(timestamp_str.replace("Z", "+00:00"))

print("ISO 8601 datetime:", dt_iso)

This is the cleanest method when working with modern APIs.

Handle Errors When Converting String to Datetime in Python

In real-world projects, I often deal with messy data. Some strings are in the wrong format or are missing timezone info.

That’s why I always wrap my parsing code in a try-except block.

from datetime import datetime

timestamp_str = "invalid-date"

try:
    dt = datetime.strptime(timestamp_str, "%Y-%m-%d %H:%M:%S")
    print("Converted datetime:", dt)
except ValueError as e:
    print("Error converting string:", e)

This way, my Python script doesn’t crash when it encounters bad data.

Best Practices I Follow

Over the years, I’ve learned a few best practices when converting Python strings to datetime with timezone:

  • Always use UTC internally and convert to local time only when displaying to users.
  • Use pytz or zoneinfo for accurate timezone handling in the USA.
  • Validate input strings before parsing to avoid runtime errors.
  • Store datetime objects in databases with timezone awareness.

When I first started working with Python, I underestimated how tricky time zones could be. But once I mastered these methods, handling datetime strings became second nature.

Now, whenever I get a timestamp string, whether from a New York server, a California API, or a UTC-based service, I know exactly how to convert it to a timezone-aware datetime in Python.

Yoy may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.