Parse a string into a Python datetime

Use strptime for a known format, fromisoformat for supported ISO forms, and explicit timezone and ambiguity rules when parsing dates.

Best practices
Python programming and application logging

Use datetime.strptime(text, format) when you know the expected input layout. The resulting datetime is naive unless the parsed format supplies timezone information.

from datetime import datetime

text = "2024-01-15 10:30:00"
dt = datetime.strptime(text, "%Y-%m-%d %H:%M:%S")
print(dt)  # 2024-01-15 10:30:00

Invalid dates or an incompatible layout raise ValueError. Some directives accept optional leading zeros, so strptime is not a universal byte-for-byte format validator.

Common directives

Directive Meaning Example
%Y Year including century 2024
%m Month 01
%d Day of month 15
%H Hour on a 24-hour clock 10
%M Minute 30
%S Second 00
%f Fractional second, one to six digits 123456
%z UTC offset +0800

%f pads shorter fractions on the right, so .123 becomes 123,000 microseconds. Use %z when the input supplies an offset and you need an aware datetime.

Parse an ISO-style value

dt = datetime.fromisoformat("2024-01-15T10:30:00+08:00")
print(dt.utcoffset())  # 8:00:00

fromisoformat() was added in Python 3.7 and its accepted forms expanded in later releases, notably 3.11. Check your supported version before assuming every ISO 8601 variant, such as a trailing Z, is accepted. A numeric offset identifies an offset, not a named regional timezone with all its daylight-saving rules.

Use flexible parsing deliberately

With python-dateutil installed:

from dateutil import parser

dt = parser.parse("Jan 15, 2024 10:30 AM")

Flexible parsing is useful for varied inputs, but an ambiguous date such as 01/02/2024 still needs a day/month policy. Missing fields can be filled from defaults. For a controlled API or log format, a specified format is usually easier to validate than heuristic parsing.

Format the result again

print(dt.strftime("%Y-%m-%d %H:%M:%S"))
print(dt.isoformat())

Formatting does not add a timezone that the datetime never had.

FAQ

Why does parsing raise ValueError? Inspect the input, separator characters, date validity, and chosen directives. Do not automatically switch to a permissive parser if malformed input should be rejected.

How do I parse milliseconds? Include .%f, as in %Y-%m-%d %H:%M:%S.%f. Three fractional digits are valid and represent milliseconds.

Will my log collector do this automatically? Only when its parsing configuration recognizes the timestamp field, format, timezone, and units. For Guance, configure the relevant DataKit or Pipeline parser and verify the resulting event timestamp against a known sample.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting