








You turn a text timestamp into a datetime object with datetime.strptime() when
the layout never changes. You use datetime.fromisoformat() for ISO strings from
APIs and logs.
from datetime import datetime
dt = datetime.strptime("2024-06-15 10:30:00", "%Y-%m-%d %H:%M:%S")
print(dt) # 2024-06-15 10:30:00
strptime() gives you a datetime.datetime you compare, subtract, or pass to
strftime(). When the text varies, install python-dateutil and call
dateutil.parser.parse().
You will work through all three parsers, the main format codes, time zones, errors,
and time.strptime() for legacy struct_time output.
Deploy your Python applications from GitHub using DigitalOcean App Platform. Let DigitalOcean focus on scaling your app.
datetime.strptime(string, format) needs a known layout. Both arguments are
strings.datetime.fromisoformat(string) fits ISO 8601 values like
2024-06-15T10:30:00+05:30 on Python 3.11 and later.dateutil.parser.parse(string) guesses the layout. Use this for user input, not
million-row CSV jobs.strftime() writes a string from a datetime. Remember: parse =
strptime, format = strftime..date() and .time() drop the parts you do not need.ValueError. Wrap imports in try/except or loop over
format strings.%z handles offsets like +0530. fromisoformat() handles +05:30 with the
colon on Python 3.11+.time.strptime() returns struct_time. Most apps should call
datetime.strptime() instead.Python 3.8 or later. Python 3.11+ gives you the widest fromisoformat() support.
You know strings and the datetime module.
Optional: python-dateutil. Install with
pip:
pip install python-dateutil
| Method | Format string required | Dependency | Timezone-aware | Best for |
|---|---|---|---|---|
datetime.strptime() |
Yes | stdlib | With %z |
Logs, CSVs, fixed layouts |
datetime.fromisoformat() |
No | stdlib | Yes (3.11+) | JSON/API ISO timestamps |
dateutil.parser.parse() |
No | python-dateutil |
Often | Mixed or human-readable dates |
time.strptime() |
Yes | stdlib | Limited | Legacy C-style struct_time |
strptime format directives| Directive | Meaning | Example input | Parsed part |
|---|---|---|---|
%Y |
4-digit year | 2024 |
2024 |
%y |
2-digit year | 24 |
2024 |
%m |
Month (01-12) | 06 |
June |
%d |
Day (01-31) | 15 |
15th |
%H |
Hour 24h (00-23) | 14 |
2 p.m. |
%I |
Hour 12h (01-12) | 02 |
2 (with %p) |
%M |
Minute | 30 |
30 |
%S |
Second | 00 |
0 |
%f |
Microsecond | 123456 |
123456 µs |
%p |
AM/PM | PM |
afternoon |
%z |
UTC offset | +0530 |
+5:30 |
%Z |
Time zone name | UTC |
name (platform-dependent) |
%A / %a |
Weekday full / abbr | Friday / Fri |
weekday |
%B / %b |
Month full / abbr | June / Jun |
month |
See the full list in the strftime() and strptime() format codes docs.
datetime.strptime()datetime.strptime(date_string, format) matches your format codes to the string
and returns a datetime object.
from datetime import datetime
datetime_str = '09/19/22 13:55:26'
datetime_object = datetime.strptime(datetime_str, '%m/%d/%y %H:%M:%S')
print(type(datetime_object))
print(datetime_object)
Output:
<class 'datetime.datetime'>
2022-09-19 13:55:26
date or time onlyfrom datetime import datetime
date_str = '09-19-2022'
date_object = datetime.strptime(date_str, '%m-%d-%Y').date()
print(date_object) # 2022-09-19
time_str = '13:55:26'
time_object = datetime.strptime(time_str, '%H:%M:%S').time()
print(time_object) # 13:55:26
mm dd yyyy and ISO-style stringsfrom datetime import datetime
print(datetime.strptime("12 25 2024", "%m %d %Y"))
print(datetime.strptime("2024-12-25", "%Y-%m-%d"))
# Three-digit milliseconds use %f (microseconds). Python pads with zeros.
print(datetime.strptime("2024-06-15 10:30:00.123", "%Y-%m-%d %H:%M:%S.%f"))
Output:
2024-12-25 00:00:00
2024-12-25 00:00:00
2024-06-15 10:30:00.123000
fromisoformat()datetime.fromisoformat() reads many ISO 8601 strings with no manual format
string. You see this shape in REST APIs and databases.
from datetime import datetime
print(datetime.fromisoformat("2024-06-15T10:30:00"))
print(datetime.fromisoformat("2024-06-15T10:30:00+05:30"))
Output:
2024-06-15 10:30:00
2024-06-15 10:30:00+05:30
Python version notes:
YYYY-MM-DD and basic T separators.dateutil.parser.parse() on odd strings.Strings ending in Z mean UTC. On older Python, swap Z for +00:00 first:
s = "2024-06-15T10:30:00Z"
dt = datetime.fromisoformat(s.replace("Z", "+00:00"))
dateutilWhen each row looks different, dateutil.parser.parse() infers the layout:
from dateutil import parser
print(parser.parse("Jun 1 2005 1:33PM"))
print(parser.parse("2024-06-15"))
Run pip install python-dateutil first.
parse() costs more CPU on huge files because the library inspects each string.
Stick with strptime() when every row shares one format.
You do not need dateutil for Jun 1 2005 1:33PM. Spell out the format:
from datetime import datetime
s = "Jun 1 2005 1:33PM"
dt = datetime.strptime(s, "%b %d %Y %I:%M%p")
print(dt)
Output:
2005-06-01 13:33:00
There is no space before %p because the input runs PM right after the minutes.
Numeric offset with strptime() and %z. The offset has no colon:
from datetime import datetime
dt = datetime.strptime("2024-06-15 10:30:00+0530", "%Y-%m-%d %H:%M:%S%z")
print(dt) # timezone-aware
ISO offset with a colon works on Python 3.11+ through fromisoformat():
from datetime import datetime
dt = datetime.fromisoformat("2024-06-15T10:30:00+05:30")
Named zones like America/New_York need zoneinfo (stdlib in Python 3.9+).
Parse the naive local time, then attach the zone. Read
How to Get the Current Date and Time in Python
for worked examples.
ValueError and multiple formatsExtra text or a wrong format raises ValueError:
from datetime import datetime
datetime_str = '09/19/18 13:55:26'
try:
datetime.strptime(datetime_str, '%m/%d/%y')
except ValueError as err:
print(err) # unconverted data remains: 13:55:26
Loop over formats until one succeeds:
from datetime import datetime
def parse_flexible(value: str):
formats = ("%Y-%m-%d", "%m/%d/%Y", "%d-%m-%Y")
for fmt in formats:
try:
return datetime.strptime(value, fmt)
except ValueError:
continue
raise ValueError(f"no format matched: {value!r}")
print(parse_flexible("2024-06-15"))
Log the raw string when a row fails. You fix bad data faster.
datetime back to a string with strftime()strftime() reverses strptime(). You go from object to string.
from datetime import datetime
date_object = datetime.strptime("12 25 2024", "%m %d %Y")
print(date_object.strftime("%Y-%m-%d")) # 2024-12-25
print(date_object.strftime("%d, %m, %Y")) # 25, 12, 2024
Use this for yyyy-mm-dd filenames, SQL literals, or JSON fields.
time.strptime() (struct_time)The time module exposes time.strptime(). You get a time.struct_time tuple, not
a datetime object:
import time
time_str = 'Mon Dec 12 14:55:02 2022'
time_obj = time.strptime(time_str) # default format
print(time_obj.tm_year, time_obj.tm_mon, time_obj.tm_mday)
Omit the format and Python expects '%a %b %d %H:%M:%S %Y'.
Build a datetime from the tuple when you need one:
from datetime import datetime
import time
struct = time.strptime("Mon Dec 12 14:55:02 2022")
print(datetime(*struct[:6]))
New projects should default to datetime.strptime().
pandas.to_datetime() converts whole columns. Pass format like strptime, or
leave format=None to infer:
import pandas as pd
df = pd.DataFrame({"logged_at": ["2024-06-15", "2024-06-16"]})
df["logged_at"] = pd.to_datetime(df["logged_at"], format="%Y-%m-%d")
print(df.dtypes)
Mixed formats in one column? Set errors="coerce" so bad rows become NaT
instead of crashing the job. Start with the
Pandas module tutorial
if DataFrames are new to you.
Non-English month names need a locale your OS provides:
from datetime import datetime
import locale
locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
dt = datetime.strptime('16-Dezember-2022', '%d-%B-%Y')
print(dt)
If setlocale fails, install the language pack or keep month names in English and
match them with %B or %b.
You call datetime.strptime() with a format string:
from datetime import datetime
dt = datetime.strptime("2024-12-25", "%Y-%m-%d")
ISO timestamps go through datetime.fromisoformat("2024-12-25T10:30:00").
strptime() do?strptime() means string parse time. You supply format codes (%Y, %m, %d,
and others). Python returns a datetime. The time module version returns
struct_time. Neither function guesses the layout.
strftime() in Python?strftime() formats a datetime into a string. The codes match strptime(), but
the direction flips. dt.strftime("%Y-%m-%d") prints 2024-06-15.
strptime() and strftime() together?Parse, change the object, then format:
from datetime import datetime
raw = "12/25/2024"
dt = datetime.strptime(raw, "%m/%d/%Y")
iso = dt.strftime("%Y-%m-%d")
print(iso) # 2024-12-25
Parse first, then call .timestamp() for Unix seconds:
from datetime import datetime
dt = datetime.strptime("2024-06-15 10:30:00", "%Y-%m-%d %H:%M:%S")
print(int(dt.timestamp()))
Aware datetimes use UTC rules. For struct_time, use time.mktime() on the tuple
from time.strptime() (local clock semantics).
date instead of a datetime?Parse, then call .date():
from datetime import datetime
d = datetime.strptime("12 25 2024", "%m %d %Y").date()
print(d) # 2024-12-25
dateutil.parser.parse() slower than strptime()?Yes on large uniform files. dateutil inspects every string. Fixed-format CSV
and log columns run faster with strptime() or pandas.to_datetime(). See the
Pandas module tutorial.
You now have three paths: strptime() for fixed layouts, fromisoformat() for
ISO API fields, and dateutil.parser when the text varies. Add time zone handling
before production, wrap untrusted input in try/except, and reach for
strftime() when you export strings again.
Keep going with Python tutorials,
str() and repr() in Python, and the official datetime documentation.
Run timestamp pipelines on DigitalOcean App Platform without managing servers.
This work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。