Fundamentals 5 min read

Master Python DateTime Parsing: Quick Solutions for Complex Formats

This article walks through a common Python datetime parsing problem, presents multiple code solutions with explanations and results, adds a handy UTC‑to‑Beijing conversion function, and provides a reference table for format symbols, helping readers handle date strings confidently.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Python DateTime Parsing: Quick Solutions for Complex Formats

1. Introduction

Hello, I am a Python enthusiast. Yesterday a member asked about handling a Python datetime string, as shown in the image below.

2. Implementation

Two similar methods were shared. The first answer provides the following code:

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)

The execution result is shown below:

A second contributor offered an alternative implementation:

from datetime import datetime
day = "Wed Aug 03 19:48:03 +0800 2022"
res = datetime.strptime("Wed Aug 03 19:48:03 +0800 2022", "%a %b %d %H:%M:%S +0800 %Y")
print(res)

The corresponding output is displayed in the following image:

A third, more concise answer was shared as an image:

All solutions successfully resolved the original datetime parsing issue.

Additionally, a reference table for datetime format symbols is provided (image below).

3. UTC to Beijing Conversion

def utc_to_datetime(india_time_str):
    """格林威治时间(UTC)转北京时间 "%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.datetime.strptime(india_time_str, india_format)
    local_dt = india_dt + datetime.timedelta(hours=8)
    local_format = "%Y-%m-%d %H:%M:%S"
    time_str = local_dt.strftime(local_format)
    return time_str

4. Summary

This article collected a basic Python datetime conversion problem, explained the issue, and provided concrete code implementations that helped the community solve it. Thanks to the contributors for their insights and code snippets.

PythonCode examplesstrftimestrptimeUTC conversion
Python Crawling & Data Mining
Written by

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!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.