The parser from dateutil is your friend.

You'll have to pip install dateutil but you've save bags and bags of date conversion code:

pip install python-dateutil

You can use it like this.

from dateutil import parser
ds = '2012-03-01T10:00:00Z' # or any date sting of differing formats.
date = parser.parse(ds)

You'll find you can deal with almost any date string formats with this parser and you'll get a nice standard python date back

Answer from Matt Alcock on Stack Overflow
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ parse date string: best way to parse string containing utc
r/learnpython on Reddit: Parse date string: Best way to parse string containing UTC
January 19, 2022 -

Hi.

Consider this text string: 2021-01-01 01:01:00 UTC.

What's the best way of parsing this into a date object in Python 3? I could remove the "UTC" from the text, and then use something like datetime.strptime(date_string, format), but isn't there an easier way, like doesn't Python already have support for parseing strings like these?

Discussions

python - How to convert local time string to UTC? - Stack Overflow
For anyone who is confused with the most upvoted answer. You can convert a datetime string to utc time in python by generating a datetime object and then you can use astimezone(pytz.utc) to get datetime in utc. More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to convert UTC datetime string to local datetime in Python? - Python - Data Science Dojo Discussions
Hi, I have a string representing a datetime in UTC format, and I want to convert it to the local timezone. Iโ€™ve tried using datetime.strptime() and pytz but Iโ€™m not getting the expected results. Hereโ€™s my code: This code runs without errors, but the output is incorrect. More on discuss.datasciencedojo.com
๐ŸŒ discuss.datasciencedojo.com
1
0
May 8, 2023
python - Convert UTC datetime string to local datetime - Stack Overflow
I've never had to convert time to and from UTC. Recently had a request to have my app be timezone aware, and I've been running myself in circles. Lots of information on converting local time to UTC, More on stackoverflow.com
๐ŸŒ stackoverflow.com
datetime - How to get an UTC date string in Python? - Stack Overflow
I prefer the first approach, as it gets you in the habit of using timezone aware datetimes - but as J.F. Sebastian pointed out - it requires Python 3.2+. The second approach will work in both 2.7 and 3.2 branches. More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ library โ€บ datetime.html
datetime โ€” Basic date and time types
Changed in version 3.5: Before Python 3.5, a time object was considered to be false if it represented midnight in UTC. This behavior was considered obscure and error-prone and has been removed in Python 3.5. See bpo-13936 for more information. ... Return a time corresponding to a time_string in any valid ISO 8601 format, with the following exceptions:
Top answer
1 of 16
390

First, parse the string into a naive datetime object. This is an instance of datetime.datetime with no attached timezone information. See its documentation.

Use the pytz module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime.

Finally, use datetime.astimezone() method to convert the datetime to UTC.

Source code, using local timezone "America/Los_Angeles", for the string "2001-2-3 10:11:12":

from datetime import datetime   
import pytz

local = pytz.timezone("America/Los_Angeles")
naive = datetime.strptime("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S")
local_dt = local.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)

From there, you can use the strftime() method to format the UTC datetime as needed:

utc_dt.strftime("%Y-%m-%d %H:%M:%S")
2 of 16
265

NOTE -- As of 2020 you should not be using .utcnow() or .utcfromtimestamp(xxx). As you've presumably moved on to python3,you should be using timezone aware datetime objects.

>>> from datetime import timezone
>>> 
>>> # alternative to '.utcnow()'
>>> dt_now = datetime.datetime.now(datetime.timezone.utc)
>>>
>>> # alternative to '.utcfromtimestamp()'
>>> dt_ts = datetime.fromtimestamp(1571595618.0, tz=timezone.utc)

For details see: https://blog.ganssle.io/articles/2019/11/utcnow.html

original answer (from 2010):

The datetime module's utcnow() function can be used to obtain the current UTC time.

>>> import datetime
>>> utc_datetime = datetime.datetime.utcnow()
>>> utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2010-02-01 06:59:19'

As the link mentioned above by Tom: http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/ says:

UTC is a timezone without daylight saving time and still a timezone without configuration changes in the past.

Always measure and store time in UTC.

If you need to record where the time was taken, store that separately. Do not store the local time + timezone information!

NOTE - If any of your data is in a region that uses DST, use pytz and take a look at John Millikin's answer.

If you want to obtain the UTC time from a given string and you're lucky enough to be in a region in the world that either doesn't use DST, or you have data that is only offset from UTC without DST applied:

--> using local time as the basis for the offset value:

>>> # Obtain the UTC Offset for the current system:
>>> UTC_OFFSET_TIMEDELTA = datetime.datetime.utcnow() - datetime.datetime.now()
>>> local_datetime = datetime.datetime.strptime("2008-09-17 14:04:00", "%Y-%m-%d %H:%M:%S")
>>> result_utc_datetime = local_datetime + UTC_OFFSET_TIMEDELTA
>>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2008-09-17 04:04:00'

--> Or, from a known offset, using datetime.timedelta():

>>> UTC_OFFSET = 10
>>> result_utc_datetime = local_datetime - datetime.timedelta(hours=UTC_OFFSET)
>>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2008-09-17 04:04:00'

UPDATE:

Since python 3.2 datetime.timezone is available. You can generate a timezone aware datetime object with the command below:

import datetime

timezone_aware_dt = datetime.datetime.now(datetime.timezone.utc)

If your ready to take on timezone conversions go read this:

https://medium.com/@eleroy/10-things-you-need-to-know-about-date-and-time-in-python-with-datetime-pytz-dateutil-timedelta-309bfbafb3f7

๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ converting-to-utc-time
Converting datetime to UTC in Python - Python Morsels
December 20, 2021 - While Python's datetime objects do have a utcnow method: >>> datetime.datetime.utcnow() datetime.datetime(2030, 4, 1, 8, 15, 59, 89013) This method was deprecated in Python 3.12 and the Python documentation recommends passing the target timezone ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ convert-string-to-datetime-in-python-with-timezone
Convert string to datetime in Python with timezone - GeeksforGeeks
July 23, 2025 - Explanation: arrow.get(s) parses the date-time string s into an Arrow datetime object with timezone support, without requiring an explicit format string, providing a clean and user-friendly API.
๐ŸŒ
Data Science Dojo
discuss.datasciencedojo.com โ€บ python
How to convert UTC datetime string to local datetime in Python? - Python - Data Science Dojo Discussions
May 8, 2023 - Hi, I have a string representing a datetime in UTC format, and I want to convert it to the local timezone. Iโ€™ve tried using datetime.strptime() and pytz but Iโ€™m not getting the expected results. Hereโ€™s my code: This cโ€ฆ
Find elsewhere
Top answer
1 of 16
597

If you don't want to provide your own tzinfo objects, check out the python-dateutil library. It provides tzinfo implementations on top of a zoneinfo (Olson) database such that you can refer to time zone rules by a somewhat canonical name.

from datetime import datetime
from dateutil import tz

# METHOD 1: Hardcode zones:
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('America/New_York')

# METHOD 2: Auto-detect zones:
from_zone = tz.tzutc()
to_zone = tz.tzlocal()

# Since datetime.utcnow() is deprecated since version 3.12 use datetime.now()
# utc = datetime.now()  
utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')

# Tell the datetime object that it's in UTC time zone since 
# datetime objects are 'naive' by default
utc = utc.replace(tzinfo=from_zone)

# Convert time zone
central = utc.astimezone(to_zone)

Edit Expanded example to show strptime usage

Edit 2 Fixed API usage to show better entry point method

Edit 3 Included auto-detect methods for timezones (Yarin)

2 of 16
78

Here's a resilient method that doesn't depend on any external libraries:

from datetime import datetime
import time

def datetime_from_utc_to_local(utc_datetime):
    now_timestamp = time.time()
    offset = datetime.fromtimestamp(now_timestamp) - datetime.utcfromtimestamp(now_timestamp)
    return utc_datetime + offset

This avoids the timing issues in DelboyJay's example. And the lesser timing issues in Erik van Oosten's amendment.

As an interesting footnote, the timezone offset computed above can differ from the following seemingly equivalent expression, probably due to daylight savings rule changes:

offset = datetime.fromtimestamp(0) - datetime.utcfromtimestamp(0) # NO!

Update: This snippet has the weakness of using the UTC offset of the present time, which may differ from the UTC offset of the input datetime. See comments on this answer for another solution.

To get around the different times, grab the epoch time from the time passed in. Here's what I do:

def utc2local(utc):
    epoch = time.mktime(utc.timetuple())
    offset = datetime.fromtimestamp(epoch) - datetime.utcfromtimestamp(epoch)
    return utc + offset
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ convert-datetime-to-utc-timestamp-in-python
Convert Datetime to UTC Timestamp in Python - GeeksforGeeks
July 1, 2025 - In this method, the datetime is converted to a UTC time tuple using .utctimetuple() and then calendar.timegm() computes the timestamp.
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
How to convert the Zulu datetime to UTC with offset in python and spark sql - Python Help - Discussions on Python.org
August 11, 2022 - I have the below date time in string type. I want to convert that into UTC with offset > spark = SparkSession.builder.appName("Test").enableHiveSupport().getOrCreate() > print("Print statement-1") > schema = StructType([ > StructField("author", StringType(), False), > StructField("dt", StringType(), False) > ]) > > data = [ > ["author1", "2022-07-22T09:25:47.261Z"], > ["author2", "2022-07-22T09:26:47.291Z"], > ["author3", "2022-07-...
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ converting-strings-to-datetime-in-python
Converting Strings to datetime in Python
June 21, 2023 - Both datetimes will print different ... expected, the date-times are different since they're about 5 hours apart. Python's datetime module can convert all different types of strings to a datetime object....
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.to_datetime.html
pandas.to_datetime โ€” pandas 3.0.1 documentation - PyData |
If parsing datetimes with mixed time zones, please specify utc=True. ... Cast argument to a specified dtype. ... Convert argument to timedelta. ... Convert dtypes. ... scalars can be int, float, str, datetime object (from stdlib datetime module or numpy). They are converted to Timestamp when possible, otherwise they are converted to datetime.datetime.
๐ŸŒ
DEV Community
dev.to โ€บ behainguyen โ€บ python-local-date-time-and-utc-date-time-4cl7
Python: local date time and UTC date time. - DEV Community
February 11, 2023 - The time zone name for the local date time is None, and UTC for UTC date time. These are in conformance with datetime.tzname(). However, the first time I wrote this code, I was expecting either AUS Eastern Standard Time or AUS Eastern Summer Time for the local date time! ๐Ÿ˜‚ This leads to datetime.astimezone(tz=None).
๐ŸŒ
Python Guides
pythonguides.com โ€บ convert-a-string-to-datetime-in-python
Convert Python String to Datetime with Timezone
September 23, 2025 - 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.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ get-utc-timestamp-in-python
Get UTC timestamp in Python - GeeksforGeeks
April 7, 2025 - Syntax: time.tzname() Return: It will return the tuple of strings Example 1: Python program to get the DST and non ... DateTime class of the DateTime module as the name suggests contains information on both dates as well as time. Like a date object, DateTime assumes the current Gregorian calendar extended in both directions; like a time object, DateTime assumes there are exactly 3600*24 seconds in every day.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-do-i-convert-a-datetime-to-a-utc-timestamp-in-python
How do I convert a datetime to a UTC timestamp in Python?
May 19, 2025 - The calendar.timegm() function from the calendar module is used to convert a time tuple in UTC (Coordinated Universal Time) to a timestamp (seconds since epoch). This function is the inverse of time.gmtime(), which converts a timestamp to a time tuple. The timetuple() method in Python converts ...
๐ŸŒ
PYnative
pynative.com โ€บ home โ€บ python โ€บ python datetime โ€บ python string to datetime using strptime()
Python String to DateTime using Strptime() [5 Ways] โ€“ PYnative
December 5, 2021 - date_str = "23/Feb/2021:09:15:26 +0200" # %z to convert UTC offset to date dt_obj1 = datetime.strptime(date_str, "%d/%b/%Y:%H:%M:%S %z") print("Date Object With UTC offset::", dt_obj1) # Date String with Timezone Name. date_str2 = "23/Feb/2012:09:15:26 UTC +0900" # %Z %z to convert string with timezone to date dt_obj2 = datetime.strptime(date_str2, "%d/%b/%Y:%H:%M:%S %Z %z") print("Date Object With Timezone Name::", dt_obj2)Code language: Python (python) Run
๐ŸŒ
Vultr
docs.vultr.com โ€บ python โ€บ examples โ€บ convert-string-to-datetime
Python Program to Convert String to Datetime | Vultr Docs
November 22, 2024 - This snippet demonstrates converting a string with a timezone offset into a UTC datetime object with the use of pytz.