PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » Python DateTime » Python String to DateTime using strptime()

Python String to DateTime using strptime()

Updated on: December 5, 2021 | 2 Comments

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
    • Example: Parse String to Datetime
  • String to Date Object
  • String to time Object
    • String to time Object using Time Module
  • 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
    • Parsing String to DateTime Using dateutil
    • Parsing String to DateTime Using Arrow
    • Parsing String to Date using Maya

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

  1. Import datetime module

    Python’s datetime module provides functions that handle many complex functionalities involving the date and time.
    Import datetime class using a from datetime import datetime statement

  2. Use strptime() function of a datetime class

    Use datetime.strptime(date_string, format) to convert a given string into a datetime object as per the corresponding format.
    The format codes are standard directives for mentioning the format of the string for parsing. For example, The %d-%m-%Y format codes are for dd-mm-yyyy

  3. Use strptime() function of a time module

    Use this step if you want to convert a string to a time object. Use the time.strptime(string[, format]) function. This function converts time in string format to a time object in time.struct_time format.

strptime() to convert string to datetime
strptime() to convert string to DateTime

Example: Parse String to Datetime

Syntax:

datetime.strptime(date_string, format)

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).

from datetime import datetime

# Date String in dd/mm/yyyy HH:MM:SS format
dt_string = "12/06/2021 09:15:32"

# Convert string to datetime object
dt_object = datetime.strptime(dt_string, "%d/%m/%Y %H:%M:%S")
print(dt_object)

# Output 2021-06-12 09:15:32

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 the date object from the datetime instance.

Example:

from datetime import datetime

# convert yyyy-mm-dd string to date object
dt_object = datetime.strptime("2021/06/27 09:15:32", "%Y/%m/%d %H:%M:%S").date()
print(dt_object)

# Output 2021-06-27

Note: If a string represents the date without time, use only %d/%m/%Y format codes.

d_object = datetime.strptime("2021/06/27", "%Y/%m/%d").date()

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 the time object from the datetime instance.
from datetime import datetime

# Convert string to datetime.time object
time_obj = datetime.strptime("12/06/2021 09:15:32", "%d/%m/%Y %H:%M:%S").time()
print(time_obj)

# Output 09:15:32

Note: If a string represents the time without date, use only %H/%M/%S format codes.

t_object = datetime.strptime("11:45:23", "%H:%M:%S").time()

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])

Let us see with an example where we have a string mentioning the time in the hours-minutes-seconds format (hh:mm:ss).

Example:

import time

# time hours-minutes-seconds format
time_string = "09-15-09"
format_codes = "%H-%M-%S"

time_obj = time.strptime(time_string, format_codes)
print("Time Object", time_obj)
print(type(time_obj))

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-except block.

from datetime import datetime

birthday = '23-02-2021 09:13:00'
try:
    datetime_object = datetime.strptime(birthday, '%d-%m-%Y')
except ValueError as message:
    print('A value error is raised because :', message)

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.

DirectiveDescriptionExample
%dDay of the month as a zero-padded decimal number.Sun, Mon, …, Sat (en_US);
So, Mo, …, Sa (de_DE)
%mMonth of the year as a zero-padded decimal number.Sunday, Monday, …, Saturday (en_US);
Sonntag, Montag, …, Samstag (de_DE)
%YA year with a century in four-digit format0001, 2021, … , 9999
%yA year without a century in two-digit format01, 21, …, 31
%AFull name of a weekday as per the locale’s name.
Sunday, …, Saturday (en_US);
Sonntag, …, Samstag (de_DE)
%aShort name of a weekday as the locale’s abbreviated name.Sun, …, Sat (en_US);
So, …, Sa (de_DE)
%BFull name of a month as per the locale’s nameJanuary, …, December (en_US);
Januar, …, Dezember (de_DE)
%bShort name of a month as the locale’s abbreviated name.Jan, …, Dec (en_US);
Jan, …, Dez (de_DE)
%HHour (24-hour clock) as a zero-padded decimal number.01, 02, … , 23
%IHour (12-hour clock) as a zero-padded decimal number.01, 02, …, 12
%pLocale’s equivalent of either AM or PM.AM, PM (en_US);
am, pm (de_DE)
%MMinute as a zero-padded decimal number.00, 01, …, 59
%SSecond as a zero-padded decimal number.00, 01, …, 59
%fMicrosecond as a decimal number, zero-padded on the left.000000, 000001, …, 999999
%zUTC offset in the form ±HHMM[SS[.ffffff]] (empty string if the object is naive).(empty), +0000, -0400, +1030, +063415, -030712.345216
%ZTime zone name (empty string if the object is naive).
(empty), UTC, GMT
%jDay of the year as a zero-padded decimal number.001, 002, …, 366
%UWeek 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
%WWeek 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
%cLocale’s appropriate date and time representation.Tue Aug 16 21:30:00 1988 (en_US);
Di 16 Aug 21:30:00 1988 (de_DE)
%xLocale’s appropriate date representation.08/16/88 (None);
08/16/1988 (en_US);
16.08.1988 (de_DE)
%XLocale’s appropriate time representation.21:30:00 (en_US);
21:30:00 (de_DE)
%%A literal '%' character.%
strptime() Date format codes

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

from datetime import datetime

# String with full day and month name
date_str = "Wednesday,10 February,2021 12:19:47"

# %A is to parse weekday and %B to parse month name
dt_obj = datetime.strptime(date_str, "%A,%d %B,%Y %H:%M:%S")
print("Date Object:", dt_obj)

# Output  2021-02-10 12:19:47

Example 2: String with abbreviated Day and Month Names

from datetime import datetime

# String with full day and month name
date_str = "Wed,10 Feb,21"

# %a is to parse short weekday and %b to parse short month name
dt_obj = datetime.strptime(date_str, "%a,%d %b,%y")
print("Date Object:", dt_obj)

# Output Date Object: 2021-02-10 00:00:00

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

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:

from datetime import datetime

# Date string with UTC Offset.
date_str = "23/Feb/2021:09:15:26 +0200"
# %z to convert UTC offset to date
dt_obj1 = datetime.strptime(date_str, "%d/%b/%Y:%H:%M:%S %z")
print("Date Object With UTC offset::", dt_obj1)

# Date String with Timezone Name.
date_str2 = "23/Feb/2012:09:15:26 UTC +0900"
# %Z %z to convert string with timezone to date
dt_obj2 = datetime.strptime(date_str2, "%d/%b/%Y:%H:%M:%S %Z %z")
print("Date Object With Timezone Name::", dt_obj2)

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:

import locale
from datetime import datetime

locale.setlocale(locale.LC_ALL, 'de_DE')
# de_DE locale
date_german = '23-Februar-2021 Donnerstag'

datetime_obj = datetime.strptime(date_german, '%d-%B-%Y %A')
print(datetime_obj)

# Output 2012-02-23 00:00:00

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.

from datetime import datetime

# Date string with UTC Offset.
iso_date = '2021-02-23T09:15:24+0200'
x = datetime.strptime(iso_date, "%Y-%m-%dT%H:%M:%S%z")
print('DateTIme Object with ISO Date', x)

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 to datetime.
  • Next, use the timestamp() function to extract the timestamp information

Example:

from datetime import datetime

# String to Date
birthday = "23/02/2012 09::30::23"

# String to timestamp
timeStamp = datetime.strptime(birthday, "%d/%m/%Y %H::%M::%S").timestamp()
print("TimeStamp::", timeStamp)

# Output 1329969623.0

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

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.
from dateutil.parser import parse
from dateutil.tz import gettz

tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")}
x = parse("2012-02-23 09:21:00 BRST", tzinfos=tzinfos)
print('DateTime', x)
print(type(x))

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

Example:

Use the arrow.get() method to parse a string to date.

# importing arrow module 
import arrow

# date in string format 
birthday = '2012-02-23 09:15:45'

# parsing string into date 
date = arrow.get(birthday, 'YYYY-MM-DD HH:mm:ss')

print(date)

# Output 2012-02-23T09:15:45+00:00

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

For parsing a string object to date we need to use the parse() method and the datetime() method to create the datetime object.

Example:

import maya
maya.parse("February 23 2012 09:15").datetime()

Output

datetime.datetime(2012, 2, 23, 9, 15, tzinfo=<UTC>)

Filed Under: Python, Python DateTime

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python DateTime

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Posted In

Python Python DateTime
TweetF  sharein  shareP  Pin

  Python DateTime

  • Python DateTime Guide
  • Python Get Current DateTime
  • Python DateTime Formatting
  • Python String to DateTime
  • Python Timestamp
  • Python Timedelta
  • Python TimeZones
  • List All TimeZones in Python

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com