Dates often reach your program as text: from a CSV file, a web form, a log file, or an API. Before you can compare, sort, or do arithmetic with them, you need to convert the string into a datetime object. This is called parsing.
This article is part of a series on Python Date and Time.
In this tutorial, you’ll learn how to parse a string into a datetime using strptime() and its format codes. You’ll also learn how to convert a string to a date or time object, handle errors, parse ISO 8601 strings, and use the third-party dateutil parser when the format isn’t fixed.
Table of contents
- Steps to Convert String to DateTime in Python
- String to Date Object
- String to time Object
- How strptime() works?
- strptime() Formatting Codes
- String with Day and Month Name to Datetime
- Parse String with AM/PM to a Datetime
- Parse String with Timezone to Datetime
- Parse String with Locale to DateTime
- Parsing String in ISO 8601 Date format
- Convert String to TimeStamp
- Parsing Date String with other Python libraries
- Summary
Steps to Convert String to DateTime in Python
To convert a string into a datetime object, use the strptime() method of the datetime class. For example, you may need to convert a numeric string like 13-05-2021, or a string like Thursday, 13 May 2021, to a datetime object. The steps below show how.
- Import the datetime class
Python’s datetime module has classes for working with dates and times. Import the
datetimeclass withfrom datetime import datetime. - Write the format string
Describe how your date string looks using format codes. For example,
%d-%m-%Ymeans day, month, and four-digit year separated by hyphens (dd-mm-yyyy). Every character that isn’t a format code, such as-or/, must match the string exactly. - Call strptime()
Call
datetime.strptime(date_string, format). It returns adatetimeobject, or raises aValueErrorif the string doesn’t match the format. - Extract a date or time if needed
Call
.date()or.time()on the result to keep only the date or the time part. To get atime.struct_timeinstead, usetime.strptime(string, format)from the time module.

Example: Parse String to Datetime
Syntax:
datetime.strptime(date_string, format)Code language: Python (python)
The name strptime stands for “string parse time”. Here’s an example with a string in dd/mm/yyyy hh:mm:ss format:
Output:
2021-06-12 09:15:32 <class 'datetime.datetime'> Year: 2021 | Month: 6 | Day: 12
The same date can be written in many ways. Change the format string to match the string you have:
Output:
2021-06-12 00:00:00 2021-06-12 00:00:00 2021-06-12 09:15:00 2021-06-12 00:00:00
Note: Python can’t guess whether 06/12/2021 means 6 December or 12 June. That’s why you have to give the format. Refer to Python format Datetime using strftime() for the opposite conversion, from a datetime to a string.
String to Date Object
- First, convert the string to a datetime object using
strptime(). - Then call the
date()method to keep only thedatepart.
Example:
Output:
2021-06-27 <class 'datetime.date'> 2021-06-27
For strings in the ISO format YYYY-MM-DD, there’s a shortcut: date.fromisoformat().
Output:
2021-06-27
String to time Object
To convert a string that contains a time into a datetime.time object:
- First, convert the string to a
datetimeobject. - Then call the
time()method to keep only the time part.
Output:
09:15:32 <class 'datetime.time'> 11:45:23
When the string has no date, strptime() fills in the default date 1900-01-01. That doesn’t matter here, because time() drops the date.
String to time Object using Time Module
The time module also has a strptime() function. It returns a time.struct_time object instead of a datetime.
Syntax:
time.strptime(string[, format])Code language: Python (python)
The format is optional. Without it, the default is "%a %b %d %H:%M:%S %Y", the format that time.ctime() produces.
Example: A string with time in hours-minutes-seconds format.
Output:
Time Object: time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=9, tm_min=15, tm_sec=9, tm_wday=0, tm_yday=1, tm_isdst=-1) <class 'time.struct_time'> Hour: 9
How strptime() works?
strptime() reads the string from left to right and matches it against the format:
- Each format code, such as
%dor%Y, reads one value from the string. - Every other character in the format, such as
/,-, or a space, must appear in the string exactly. - Any part of the datetime that the format doesn’t include gets a default: the date defaults to 1900-01-01 and the time to 00:00:00.
If the string doesn’t match the format, or if values are out of range (for example, month 13), strptime() raises a ValueError. You can catch it with a try-except block (see exception handling):
Output:
ValueError: unconverted data remains: 09:13:00 ValueError: time data '2021-02-23' does not match format '%d-%m-%Y' ValueError: day is out of range for month
The error message tells you what went wrong, which makes it easy to fix the format.
When your data can come in several formats, try each one until one works:
Output:
2021-02-23 2021-02-23 2021-02-23 2021-02-23
strptime() Formatting Codes
strptime() uses format codes (also called directives) to describe the string. The table below lists the most useful ones. strptime() and strftime() share the same codes.
| Directive | Description | Example |
|---|---|---|
%d | Day of the month (01 to 31) | 01, 02, …, 31 |
%m | Month as a number (01 to 12) | 01, 02, …, 12 |
%Y | Year with century, four digits | 0001, 2021, …, 9999 |
%y | Year without century, two digits. Values 00 to 68 become 2000 to 2068, and 69 to 99 become 1969 to 1999 | 00, 21, …, 99 |
%A | Full weekday name | Sunday, …, Saturday |
%a | Abbreviated weekday name | Sun, …, Sat |
%B | Full month name | January, …, December |
%b | Abbreviated month name | Jan, …, Dec |
%H | Hour, 24-hour clock | 00, 01, …, 23 |
%I | Hour, 12-hour clock (use with %p) | 01, 02, …, 12 |
%p | AM or PM | AM, PM |
%M | Minute | 00, 01, …, 59 |
%S | Second | 00, 01, …, 59 |
%f | Microsecond, 1 to 6 digits | 000000, …, 999999 |
%z | UTC offset | +0000, -0400, +05:30, Z |
%Z | Timezone name (only UTC, GMT, and your local timezone names are accepted) | UTC, GMT |
%j | Day of the year | 001, 002, …, 366 |
%U | Week number of the year, Sunday as the first day of the week | 00, 01, …, 53 |
%W | Week number of the year, Monday as the first day of the week | 00, 01, …, 53 |
%c | Locale’s date and time representation | Tue Aug 16 21:30:00 1988 |
%x | Locale’s date representation | 08/16/88 |
%X | Locale’s time representation | 21:30:00 |
%% | A literal % character | % |
The examples show the default English (C) locale. Names such as %A and %B follow the current locale, as shown below. When parsing, the leading zero is optional: %d accepts both 5 and 05.
String with Day and Month Name to Datetime
Use these format codes to parse strings that contain weekday or month names:
%A: full weekday name, like Monday or Tuesday.%a: abbreviated weekday name, like Mon or Tue.%B: full month name, like June or March.%b: abbreviated month name, like Jun or Mar.
Parsing names isn’t case-sensitive, so FEB, feb, and Feb all work.
Example 1: String with full day and month names
Output:
Date Object: 2021-02-10 12:19:47
Example 2: String with abbreviated day and month names
Output:
Date Object: 2021-02-10 00:00:00
Note: strptime() doesn’t check that the weekday is correct. "Friday, 10 February 2021" also parses, even though 10 February 2021 was a Wednesday.
Parse String with AM/PM to a Datetime
For a 12-hour clock with AM/PM, use %I for the hour and %p for AM or PM. If you use %H instead, %p is ignored and PM times come out wrong.
Output:
Morning: 2021-02-23 09:15:00 Evening: 2021-02-23 21:15:00
Parse String with Timezone to Datetime
Use the %z directive to parse a UTC offset such as +0200, +02:00, or Z. The result is a timezone-aware datetime.
Read: Working with Timezones in Python
Example:
Output:
With UTC offset: 2021-02-23 09:15:26+02:00 tzinfo: UTC+02:00 2021-02-23 09:15:26+05:30 2021-02-23 09:15:26+00:00
The %Z directive is more limited. It only accepts UTC, GMT, and the names of your computer’s local timezone, and it doesn’t attach the timezone to the result:
Output:
2021-02-23 09:15:26 | tzinfo: None
The result is naive. If you need an aware datetime, prefer strings with a numeric offset and %z, or attach the timezone yourself with dt.replace(tzinfo=timezone.utc).
Parse String with Locale to DateTime
Month and weekday names (%B, %b, %A, %a) are read in the language of the current locale. By default, Python uses English names. To parse names in another language, for example German, switch the locale with locale.setlocale() first:
The locale must be installed on your computer, otherwise setlocale() raises locale.Error: unsupported locale setting. Locale names also differ between operating systems.
Note: setlocale() changes the setting for the whole program, which can affect other code. For multi-language apps, a library such as Babel or dateutil is often a better choice.
Parsing String in ISO 8601 Date format
ISO 8601 strings such as 2021-02-23T09:15:24+02:00 are common in APIs and JSON. The easiest way to parse them is datetime.fromisoformat(). From Python 3.11 it accepts almost every ISO 8601 form, including a trailing Z. You can also use strptime() with %z:
Output:
2021-02-23 09:15:24+02:00 2021-02-23 09:15:24+00:00 2021-02-23 00:00:00 DateTime object with ISO date: 2021-02-23 09:15:24+02:00
Convert String to TimeStamp
- First, use
strptime()to convert the string to adatetimeobject. - Then call its
timestamp()method to get the timestamp (seconds since 1 January 1970 UTC).
Example:
Output:
Timestamp: 1329989423.0
If you call timestamp() on the naive datetime directly, Python assumes it’s in your computer’s local time, so the result depends on where you run the code.
Parsing Date String with other Python libraries
strptime() is strict: you must know the exact format in advance. That’s good for reliable parsing, but inconvenient when the format varies or comes from people typing freely. Third-party libraries can help in these cases.
Parsing String to DateTime Using dateutil
The dateutil library has a parser.parse() function that recognizes most date formats automatically, without a format string. Install it with:
pip install python-dateutilCode language: Python (python)
Output:
'2021-02-23 09:15' -> 2021-02-23 09:15:00 'Feb 23 2021 9:15 PM' -> 2021-02-23 21:15:00 '23 February 2021' -> 2021-02-23 00:00:00 'Tuesday, 23 Feb 2021' -> 2021-02-23 00:00:00 '2021-02-23T09:15:24+05:30' -> 2021-02-23 09:15:24+05:30
For ambiguous numeric dates like 03/04/2021, dateutil assumes month first (US style). Pass dayfirst=True if your dates are day first:
Output:
2021-03-04 00:00:00 2021-04-03 00:00:00
Other rules dateutil follows when information is missing:
- If AM or PM isn’t given, a 24-hour clock is assumed.
- If the string has no timezone, the result is a naive datetime.
- Missing parts are taken from the current date. Use the
defaultargument to provide your own defaults.
You can also map timezone abbreviations to real timezones with the tzinfos argument:
Output:
DateTime: 2012-02-23 09:21:00-02:00
datetime.datetime(2012, 2, 23, 9, 21, tzinfo=tzoffset('BRST', -7200))
Tip: Because parser.parse() guesses, it can silently misread a string. Use strptime() when you know the format, and dateutil when you don’t.
Parsing String to DateTime Using Arrow
Arrow is a third-party library with a friendlier API for creating, parsing, formatting, and converting dates. Install it with:
pip install arrowCode language: Python (python)
Use arrow.get() with a format string. Arrow uses its own tokens, such as YYYY and MM, instead of % codes:
Arrow returns a timezone-aware object in UTC by default.
Parsing String to Date using Maya
Maya is another library for parsing human-readable dates, such as maya.parse("February 23 2012 09:15").datetime(). However, Maya is no longer actively maintained, so for new code we recommend dateutil or Arrow instead.
Summary
| Task | Use |
|---|---|
| String to datetime (known format) | datetime.strptime(s, fmt) |
| String to date | datetime.strptime(s, fmt).date() or date.fromisoformat(s) |
| String to time | datetime.strptime(s, fmt).time() |
| ISO 8601 string to datetime | datetime.fromisoformat(s) |
| String to timestamp | datetime.strptime(s, fmt).timestamp() |
| Unknown format | dateutil.parser.parse(s) |
