In this tutorial, we’ll see how to parse a string to a datetime using the strptime()
with the various standard date formatting codes available in Python. In addition, we will see similar methods available in the other modules for converting a string to a date
or time
object.
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
Steps to Convert String to DateTime in Python
In some cases, date and time could be passed as a string object. To convert a string into a datetime
object, we can use the strptime()
function of a datetime module.
For example, you may need to convert a numerical string like 13-05-2021 to a datetime
object. or you want to convert string representing dates like Monday, 13 May, 2021 to a datetime
object.
The below steps shows how to convert a string representing a date to a datetime object
- Import datetime module
Python’s datetime module provides functions that handle many complex functionalities involving the date and time.
Importdatetime
class using afrom datetime import datetime
statement - Use strptime() function of a datetime class
Use
datetime.strptime(date_string, format)
to convert a given string into adatetime
object as per the correspondingformat
.
The format codes are standard directives for mentioning the format of the string for parsing. For example, The%d-%m-%Y
format codes are fordd-mm-yyyy
- Use strptime() function of a time module
Use this step if you want to convert a string to a
time
object. Use thetime.strptime(string[, format])
function. This function converts time in string format to atime
object intime.struct_time
format.
Example: Parse String to Datetime
Syntax:
datetime.strptime(date_string, format)
Code language: Python (python)
Let us see with an example where we have a string representing the date and time in the standard format (dd/mm/yyyy hh:mm:ss
).
Refer to Python format Datetime using strftime() to convert a datetime
to string
String to Date Object
- First, convert a string to a datetime object using the
strptime()
function - Use
datetime.date()
function to extract only thedate
object from the datetime instance.
Example:
Note: If a string represents the date without time, use only %d/%m/%Y
format codes.
String to time
Object
Also, you can use the datetime.time
class to convert a string containing the time to a time
object.
- First, convert a string to a
datetime
object - Use
datetime.time()
function to extract only thetime
object from the datetime instance.
Note: If a string represents the time without date, use only %H/%M/%S
format codes.
String to time
Object using Time Module
We can use the time module’s strptime
() method to convert time in string format to a time object in time.struct_time
format.
Syntax:
time.strptime(string[, format])
Code language: Python (python)
Let us see with an example where we have a string mentioning the time in the hours-minutes-seconds format (hh:mm:ss)
.
Example:
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'>
How strptime()
works?
This method basically converts the string into a datetime object according to a format.
Note: In case the string argument that is passed to the strptime()
method doesn’t match the format specified, a ValueError
will be raised.
The exception will have an error message that shows a format mismatch or extra data in the string. We can catch the error using exception handling inside a try-excep
t block.
Output:
A value error is raised because : unconverted data remains: 09:13:00
strptime()
Formatting Codes
The strptime()
takes some standard directives for mentioning the format of the string for parsing. The following table provides a summary of the available directives for the strptime()
function.
The same set of directives are shared between both the strptime()
and strftime()
methods.
Now we can see more combinations with examples for a better understanding of the directives. The below format code works on all platforms with a standard C implementation.
Directive | Description | Example |
---|---|---|
%d | Day of the month as a zero-padded decimal number. | Sun, Mon, …, Sat (en_US); So, Mo, …, Sa (de_DE) |
%m | Month of the year as a zero-padded decimal number. | Sunday, Monday, …, Saturday (en_US); Sonntag, Montag, …, Samstag (de_DE) |
%Y | A year with a century in four-digit format | 0001, 2021, … , 9999 |
%y | A year without a century in two-digit format | 01, 21, …, 31 |
%A | Full name of a weekday as per the locale’s name. | Sunday, …, Saturday (en_US); Sonntag, …, Samstag (de_DE) |
%a | Short name of a weekday as the locale’s abbreviated name. | Sun, …, Sat (en_US); So, …, Sa (de_DE) |
%B | Full name of a month as per the locale’s name | January, …, December (en_US); Januar, …, Dezember (de_DE) |
%b | Short name of a month as the locale’s abbreviated name. | Jan, …, Dec (en_US); Jan, …, Dez (de_DE) |
%H | Hour (24-hour clock) as a zero-padded decimal number. | 01, 02, … , 23 |
%I | Hour (12-hour clock) as a zero-padded decimal number. | 01, 02, …, 12 |
%p | Locale’s equivalent of either AM or PM. | AM, PM (en_US); am, pm (de_DE) |
%M | Minute as a zero-padded decimal number. | 00, 01, …, 59 |
%S | Second as a zero-padded decimal number. | 00, 01, …, 59 |
%f | Microsecond as a decimal number, zero-padded on the left. | 000000, 000001, …, 999999 |
%z | UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if the object is naive). | (empty), +0000, -0400, +1030, +063415, -030712.345216 |
%Z | Time zone name (empty string if the object is naive). | (empty), UTC, GMT |
%j | Day of the year as a zero-padded decimal number. | 001, 002, …, 366 |
%U | Week number of the year (Sunday as the first day of the week) as a zero-padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. | 00, 01, …, 53 |
%W | Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0. | 00, 01, …, 53 |
%c | Locale’s appropriate date and time representation. | Tue Aug 16 21:30:00 1988 (en_US); Di 16 Aug 21:30:00 1988 (de_DE) |
%x | Locale’s appropriate date representation. | 08/16/88 (None); 08/16/1988 (en_US); 16.08.1988 (de_DE) |
%X | Locale’s appropriate time representation. | 21:30:00 (en_US); 21:30:00 (de_DE) |
%% | A literal '%' character. | % |
String with Day and Month Name to Datetime
We can parse a string with full or abbreviated weekday and full or abbreviated month names to a datetime
object using the following format codes.
%A
: Returns the full name of the weekday. Like, Monday, Tuesday%a
: Returns the short name of the weekday (First three character.). Like, Mon, Tue%B
: Returns the full name of the month. Like, June, March%b
: Returns the short name of the month (First three character.). Like, Mar, Jun
Example 1: String with Full Day and Month Name
Example 2: String with abbreviated Day and Month Names
Parse String with AM/PM to a Datetime
We can parse a string with AM/PM details to a datetime
object using the format directive %p
.
from datetime import datetime
# String with Am Pm
date_str = "23-Feb-2021 09.15 AM"
# %p is to parse Am/Pm
dt_obj = datetime.strptime(date_str, "%d-%b-%Y %I.%M %p")
print("DateTime Object:", dt_obj)
# Output 2021-02-23 09:15:00
Code language: Python (python)
Parse String with Timezone to Datetime
We can convert a string with offset information represented as timedelta (+/-) or with the timezone names to the datetime
object using the %z
and %Z
format directives.
Read: Working with Timezones in Python
Example:
Output
Date Object With UTC offset:: 2021-02-23 09:15:26+02:00 Date Object With Timezone Name:: 2012-02-23 09:15:26+09:00
Parse String with Locale to DateTime
We can understand from the directives that strptime()
method supports both the US locale en_US and the german locale de_DE.
Example:
Parsing String in ISO 8601 Date format
We can parse string objects with dates in ISO 8601 formats using the strptime()
method where the offset could be parsed using the %z
format directive.
Output
DateTIme Object with ISO Date 2021-02-23 09:15:24+02:00
Convert String to TimeStamp
- First, use the
strptime()
method to convert a string object todatetime
. - Next, use the
timestamp()
function to extract the timestamp information
Example:
Parsing Date String with other Python libraries
While the datetime module’s strptime()
handles most of the date formats, there are few drawbacks, as mentioned below.
- We need to import many modules like
datetime
,time
,calendar
,pytz
, and more to handle some complex date formats. - Handling naive and aware timezones are complicated.
- Parsing the different locale information and formats like ISO 8601 is error-prone.
Parsing String to DateTime Using dateutil
The dateutil module offers a parser to parse the date string which offers a generic parser that parses almost all the known date/time formats available.
Note: It is a third-party module you need to install it separately using the pip command.
pip install python-dateutil
Code language: Python (python)
In case the dates are ambiguous i.e; some information is omitted, the following rules are applied.
- If AM or PM is left unspecified, a 24-hour clock is assumed; however, an hour on a 12-hour clock (0 <= hour <= 12) must be specified if AM or PM is specified.
- In case a date string is passed without the timezone information, then a naive object is created.
- If any other information is missing, then the default parameter value of the
date.datetime
object is used. If this results in a day number exceeding the valid number of days per month, the value falls back to the month’s end.
Output
datetime.datetime(2012, 2, 23, 9, 21, tzinfo=tzoffset('BRST', -7200))
Parsing String to DateTime Using Arrow
Arrow is another Python library that helps in creating the date and time objects with fewer imports and lesser code. This API enables bridge gaps in creating, formatting, and modifying dates, times, and timestamps.
Arrow helps in parsing date string formats and simplifies creating UTC by default or time-zone-aware objects.
We need first to install the arrow using the pip
.
pip install arrow
Code language: Python (python)
Example:
Use the arrow.get()
method to parse a string to date.
Parsing String to Date using Maya
Maya is another Python library mainly for dealing with different locales in different systems. This is especially helpful when the same code has to be migrated to operating systems in different timezones.
We need to install Maya using the following pip command.
pip install maya
Code language: Python (python)
For parsing a string object to date we need to use the parse
() method and the datetime()
method to create the datetime object.
Example:
Output
datetime.datetime(2012, 2, 23, 9, 15, tzinfo=<UTC>)