Introduction
You move a matter timestamp into a datetime entity pinch datetime.strptime() when the layout ne'er changes. You usage 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:00strptime() gives you a datetime.datetime you compare, subtract, aliases walk to strftime(). When the matter varies, instal python-dateutil and call dateutil.parser.parse().
You will activity done each 3 parsers, the main format codes, clip zones, errors, and time.strptime() for bequest struct_time output.
Deploy your Python applications from GitHub utilizing DigitalOcean App Platform. Let DigitalOcean attraction connected scaling your app.
Key takeaways
- 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 connected Python 3.11 and later.
- dateutil.parser.parse(string) guesses the layout. Use this for personification input, not million-row CSV jobs.
- strftime() writes a drawstring from a datetime. Remember: parse = strptime, format = strftime.
- .date() and .time() driblet the parts you do not need.
- Wrong formats raise ValueError. Wrap imports successful try/except aliases loop over format strings.
- %z handles offsets for illustration +0530. fromisoformat() handles +05:30 pinch the colon connected Python 3.11+.
- time.strptime() returns struct_time. Most apps should call datetime.strptime() instead.
- Python 3.12 and 3.13 connected Ubuntu 24.04 LTS support these APIs unchanged. Start with the stdlib earlier you adhd packages.
Prerequisites
-
Python 3.8 aliases later. Python 3.11+ gives you the widest fromisoformat() support.
-
You cognize strings and the datetime module.
-
Optional: python-dateutil. Install with pip:
pip install python-dateutil
Choose a parsing method
| 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 aliases human-readable dates |
| time.strptime() | Yes | stdlib | Limited | Legacy C-style struct_time |
Common strptime format directives
| %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 area name | UTC | name (platform-dependent) |
| %A / %a | Weekday afloat / abbr | Friday / Fri | weekday |
| %B / %b | Month afloat / abbr | June / Jun | month |
See the afloat database successful the strftime() and strptime() format codes docs.
Method 1: Parse pinch datetime.strptime()
datetime.strptime(date_string, format) matches your format codes to the string and returns a datetime object.
Parse a day and clip string
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:26Parse to day aliases clip only
from 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:26Parse mm dd yyyy and ISO-style strings
from datetime import datetime print(datetime.strptime("12 25 2024", "%m %d %Y")) print(datetime.strptime("2024-12-25", "%Y-%m-%d")) # Three-digit milliseconds usage %f (microseconds). Python pads pinch 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.123000Method 2: Parse ISO strings pinch fromisoformat()
datetime.fromisoformat() sounds galore ISO 8601 strings pinch nary manual format string. You spot this style successful 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:30Python type notes:
- 3.7+: YYYY-MM-DD and basal T separators.
- 3.11+: much ISO variants, including respective timezone forms.
- 3.6-3.10: smaller subset. Reach for dateutil.parser.parse() connected overseas strings.
Strings ending successful Z mean UTC. On older Python, switch Z for +00:00 first:
s = "2024-06-15T10:30:00Z" dt = datetime.fromisoformat(s.replace("Z", "+00:00"))Method 3: Flexible parsing pinch dateutil
When each statement 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 instal python-dateutil first.
parse() costs much CPU connected immense files because the room inspects each string. Stick pinch strptime() erstwhile each statement shares 1 format.
Parse human-readable dates pinch a fixed format
You do not request dateutil for Jun 1 2005 1:33PM. Spell retired 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:00There is nary abstraction earlier %p because the input runs PM correct aft the minutes.
Parse strings pinch timezone offsets
Numeric offset pinch strptime() and %z. The offset has nary 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-awareISO offset pinch a colon useful connected Python 3.11+ done fromisoformat():
from datetime import datetime dt = datetime.fromisoformat("2024-06-15T10:30:00+05:30")Named zones for illustration America/New_York request zoneinfo (stdlib successful Python 3.9+). Parse the naive section time, past connect the zone. Read How to Get the Current Date and Time successful Python for worked examples.
Handle ValueError and aggregate formats
Extra matter aliases a incorrect 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 information remains: 13:55:26Loop complete formats until 1 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 earthy drawstring erstwhile a statement fails. You hole bad information faster.
Convert datetime backmost to a drawstring pinch strftime()
strftime() reverses strptime(). You spell from entity 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, 2024Use this for yyyy-mm-dd filenames, SQL literals, aliases JSON fields.
Parse pinch time.strptime() (struct_time)
The clip 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 erstwhile you request 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().
Parse day columns pinch Pandas
pandas.to_datetime() converts full columns. Pass format for illustration 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 successful 1 column? Set errors="coerce" truthful bad rows go NaT instead of crashing the job. Start pinch the Pandas module tutorial if DataFrames are caller to you.
Locale-specific period names
Non-English period names request 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, instal the connection battalion aliases support period names successful English and match them pinch %B aliases %b.
Frequently asked questions
1. How do you person a drawstring to a datetime successful Python?
You telephone datetime.strptime() pinch a format string:
from datetime import datetime dt = datetime.strptime("2024-12-25", "%Y-%m-%d")ISO timestamps spell done datetime.fromisoformat("2024-12-25T10:30:00").
2. What does strptime() do?
strptime() intends drawstring parse time. You proviso format codes (%Y, %m, %d, and others). Python returns a datetime. The clip module type returns struct_time. Neither usability guesses the layout.
3. What is strftime() successful Python?
strftime() formats a datetime into a string. The codes lucifer strptime(), but the guidance flips. dt.strftime("%Y-%m-%d") prints 2024-06-15.
4. How do you usage strptime() and strftime() together?
Parse, alteration the object, past 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-255. How do you person a drawstring to a timestamp successful Python?
Parse first, past telephone .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 usage UTC rules. For struct_time, usage time.mktime() connected the tuple from time.strptime() (local timepiece semantics).
6. How do you get a day alternatively of a datetime?
Parse, past telephone .date():
from datetime import datetime d = datetime.strptime("12 25 2024", "%m %d %Y").date() print(d) # 2024-12-257. Is dateutil.parser.parse() slower than strptime()?
Yes connected ample azygous files. dateutil inspects each string. Fixed-format CSV and log columns tally faster pinch strptime() aliases pandas.to_datetime(). See the Pandas module tutorial.
What’s next
You now person 3 paths: strptime() for fixed layouts, fromisoformat() for ISO API fields, and dateutil.parser erstwhile the matter varies. Add clip area handling before production, wrap untrusted input successful try/except, and scope for strftime() erstwhile you export strings again.
Keep going pinch Python tutorials, str() and repr() successful Python, and the charismatic datetime documentation.
Run timestamp pipelines connected DigitalOcean App Platform without managing servers.
This activity is licensed nether a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
English (US) ·
Indonesian (ID) ·