How to Parse Complex Date Strings in Python: Step‑by‑Step Code Examples
This article explains how to parse intricate datetime strings in Python using the datetime module, presents multiple code solutions with full examples, and provides a reusable function to convert UTC timestamps to Beijing time, helping readers handle common time‑formatting challenges.
Introduction
Hello, I'm a Python enthusiast. Yesterday a member asked how to parse a datetime string like "Wed Aug 03 19:48:03 +0800 2022".
Implementation
Two similar solutions were provided.
from datetime import datetime
d = 'Wed Aug 03 19:48:03 +0800 2022'
r = datetime.strptime(d, '%a %b %d %X %z %Y')
print(r)Result shown in the following image:
Another answer used a slightly different format string:
from datetime import datetime
day = "Wed Aug 03 19:48:03 +0800 2022"
res = datetime.strptime(day, "%a %b %d %H:%M:%S +0800 %Y")
print(res)A concise version was also shared as an image.
Additionally, a utility function to convert UTC (or ISO format) to Beijing time was provided:
def utc_to_datetime(india_time_str):
"""Convert UTC time to Beijing time %Y-%m-%d %H:%M:%S"""
if not india_time_str:
return
if 'Z' in india_time_str:
india_format = '%Y-%m-%dT%H:%M:%S.%fZ'
else:
india_format = '%Y-%m-%dT%H:%M:%S'
india_dt = datetime.strptime(india_time_str, india_format)
local_dt = india_dt + datetime.timedelta(hours=8)
local_format = "%Y-%m-%d %H:%M:%S"
return local_dt.strftime(local_format)Conclusion
This article demonstrated how to parse complex datetime strings in Python and provided a reusable function for UTC‑to‑Beijing conversion, helping readers solve similar time‑formatting issues.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
