You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python datetime.strptime解析带冒号时区偏移的跨版本报错问题

Python 3.6 vs 3.7: Parsing Timezones with Colons

Yep, you’ve hit a classic Python version compatibility issue here! Let me break it down and give you a few solid ways to fix it.

Why the Error Happens

Python 3.6’s datetime.strptime() doesn’t support timezone offsets with colons (like +01:00) when using the %z format specifier. This support was added in Python 3.7—that’s why your code works flawlessly on Windows with 3.7.2, but throws an error on Linux with 3.6.7. The operating system doesn’t matter here; it’s purely a Python version difference.

Solutions to Parse the Time String

Pick the option that fits your environment constraints:

1. Upgrade Python to 3.7+

If you can update your Python installation on Linux to 3.7 or newer, this is the simplest fix. Your original code will work exactly as written, since 3.7+ natively handles colon-separated timezone offsets with the %z specifier.

2. Manually Fix the Time String (No Third-Party Libraries)

If upgrading isn’t an option, modify the input string to remove the colon from the timezone segment before parsing. A regex is the most reliable way to do this without messing up the colons in the time itself:

from datetime import datetime
import re

datetimestring = "2019-01-19T15:13:00.000+01:00"
# Target only the colon in the final timezone offset (e.g., +01:00 → +0100)
fixed_str = re.sub(r'([+-])(\d{2}):(\d{2})$', r'\1\2\3', datetimestring)
dt = datetime.strptime(fixed_str, '%Y-%m-%dT%H:%M:%S.%f%z')

The regex zeroes in on the last part of the string, so it won’t affect colons in the hour/minute/second sections.

3. Use the python-dateutil Library

For a robust, version-agnostic solution that handles all kinds of datetime formats (including this one) without manual string tweaks, use the python-dateutil library. It’s a go-to tool for datetime parsing in Python:
First, install it via pip:

pip install python-dateutil

Then parse your string with no format specifiers required:

from dateutil import parser

datetimestring = "2019-01-19T15:13:00.000+01:00"
dt = parser.parse(datetimestring)

This works seamlessly across all recent Python versions, including 3.6.

内容的提问来源于stack exchange,提问作者Bruno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:59:16