PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Python DateTime » Python String to DateTime using strptime()

Python String to DateTime using strptime()

Updated on: December 1, 2026 | 2 Comments

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

  1. Import the datetime class

    Python’s datetime module has classes for working with dates and times. Import the datetime class with from datetime import datetime.

  2. Write the format string

    Describe how your date string looks using format codes. For example, %d-%m-%Y means 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.

  3. Call strptime()

    Call datetime.strptime(date_string, format). It returns a datetime object, or raises a ValueError if the string doesn’t match the format.

  4. 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 a time.struct_time instead, use time.strptime(string, format) from the time module.

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

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:

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)
print(type(dt_object))

# now you can use datetime attributes
print('Year:', dt_object.year, '| Month:', dt_object.month, '| Day:', dt_object.day)Code language: Python (python)

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:

from datetime import datetime

print(datetime.strptime("2021-06-12", "%Y-%m-%d"))          # ISO style
print(datetime.strptime("06/12/2021", "%m/%d/%Y"))          # US style: month first
print(datetime.strptime("12.06.2021 9:15", "%d.%m.%Y %H:%M"))
print(datetime.strptime("20210612", "%Y%m%d"))              # no separatorsCode language: Python (python)

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 the date part.

Example:

from datetime import datetime

# string with date and time
d1 = datetime.strptime("2021/06/27 09:15:32", "%Y/%m/%d %H:%M:%S").date()
print(d1, type(d1))

# string with only a date: the format has only date codes
d2 = datetime.strptime("2021/06/27", "%Y/%m/%d").date()
print(d2)Code language: Python (python)

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

from datetime import date

print(date.fromisoformat("2021-06-27"))Code language: Python (python)

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 datetime object.
  • Then call the time() method to keep only the time part.
from datetime import datetime

# string with date and time
t1 = datetime.strptime("12/06/2021 09:15:32", "%d/%m/%Y %H:%M:%S").time()
print(t1, type(t1))

# string with only a time: use only time codes
t2 = datetime.strptime("11:45:23", "%H:%M:%S").time()
print(t2)Code language: Python (python)

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.

import time

time_string = "09-15-09"
time_obj = time.strptime(time_string, "%H-%M-%S")

print("Time Object:", time_obj)
print(type(time_obj))
print("Hour:", time_obj.tm_hour)Code language: Python (python)

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 %d or %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):

from datetime import datetime

tests = [
    ('23-02-2021 09:13:00', '%d-%m-%Y'),   # extra data in the string
    ('2021-02-23', '%d-%m-%Y'),            # wrong order
    ('31-02-2021', '%d-%m-%Y'),            # 31 February doesn't exist
]

for text, fmt in tests:
    try:
        datetime.strptime(text, fmt)
    except ValueError as error:
        print('ValueError:', error)Code language: Python (python)

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:

from datetime import datetime

FORMATS = ['%Y-%m-%d', '%d/%m/%Y', '%d %B %Y', '%b %d, %Y']

def parse_date(text):
    for fmt in FORMATS:
        try:
            return datetime.strptime(text, fmt)
        except ValueError:
            pass   # try the next format
    raise ValueError(f'Unknown date format: {text!r}')

for s in ['2021-02-23', '23/02/2021', '23 February 2021', 'Feb 23, 2021']:
    print(parse_date(s).date())Code language: Python (python)

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.

DirectiveDescriptionExample
%dDay of the month (01 to 31)01, 02, …, 31
%mMonth as a number (01 to 12)01, 02, …, 12
%YYear with century, four digits0001, 2021, …, 9999
%yYear without century, two digits. Values 00 to 68 become 2000 to 2068, and 69 to 99 become 1969 to 199900, 21, …, 99
%AFull weekday nameSunday, …, Saturday
%aAbbreviated weekday nameSun, …, Sat
%BFull month nameJanuary, …, December
%bAbbreviated month nameJan, …, Dec
%HHour, 24-hour clock00, 01, …, 23
%IHour, 12-hour clock (use with %p)01, 02, …, 12
%pAM or PMAM, PM
%MMinute00, 01, …, 59
%SSecond00, 01, …, 59
%fMicrosecond, 1 to 6 digits000000, …, 999999
%zUTC offset+0000, -0400, +05:30, Z
%ZTimezone name (only UTC, GMT, and your local timezone names are accepted)UTC, GMT
%jDay of the year001, 002, …, 366
%UWeek number of the year, Sunday as the first day of the week00, 01, …, 53
%WWeek number of the year, Monday as the first day of the week00, 01, …, 53
%cLocale’s date and time representationTue Aug 16 21:30:00 1988
%xLocale’s date representation08/16/88
%XLocale’s time representation21: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

from datetime import datetime

date_str = "Wednesday, 10 February 2021 12:19:47"

# %A parses the weekday name and %B the month name
dt_obj = datetime.strptime(date_str, "%A, %d %B %Y %H:%M:%S")
print("Date Object:", dt_obj)Code language: Python (python)

Output:

Date Object: 2021-02-10 12:19:47

Example 2: String with abbreviated day and month names

from datetime import datetime

date_str = "Wed, 10 Feb 21"

# %a parses the short weekday, %b the short month, %y the two-digit year
dt_obj = datetime.strptime(date_str, "%a, %d %b %y")
print("Date Object:", dt_obj)Code language: Python (python)

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.

from datetime import datetime

dt1 = datetime.strptime("23-Feb-2021 09.15 AM", "%d-%b-%Y %I.%M %p")
print("Morning:", dt1)

dt2 = datetime.strptime("23-Feb-2021 09.15 PM", "%d-%b-%Y %I.%M %p")
print("Evening:", dt2)Code language: Python (python)

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:

from datetime import datetime

# offset without a colon
dt1 = datetime.strptime("23/Feb/2021:09:15:26 +0200", "%d/%b/%Y:%H:%M:%S %z")
print("With UTC offset:", dt1)
print("tzinfo:", dt1.tzinfo)

# offset with a colon, and "Z" for UTC
dt2 = datetime.strptime("2021-02-23 09:15:26+05:30", "%Y-%m-%d %H:%M:%S%z")
dt3 = datetime.strptime("2021-02-23 09:15:26Z", "%Y-%m-%d %H:%M:%S%z")
print(dt2)
print(dt3)Code language: Python (python)

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:

from datetime import datetime

dt = datetime.strptime("23/Feb/2021:09:15:26 UTC", "%d/%b/%Y:%H:%M:%S %Z")
print(dt, "| tzinfo:", dt.tzinfo)Code language: Python (python)

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:

import locale
from datetime import datetime

# German locale ('de_DE' on Windows, 'de_DE.UTF-8' on Linux and macOS)
locale.setlocale(locale.LC_TIME, 'de_DE.UTF-8')

date_german = '23-Februar-2021 Dienstag'
datetime_obj = datetime.strptime(date_german, '%d-%B-%Y %A')
print(datetime_obj)   # 2021-02-23 00:00:00

# switch back to the default locale
locale.setlocale(locale.LC_TIME, '')Code language: Python (python)

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:

from datetime import datetime

# fromisoformat(): no format string needed
print(datetime.fromisoformat('2021-02-23T09:15:24+02:00'))
print(datetime.fromisoformat('2021-02-23T09:15:24Z'))      # Python 3.11+
print(datetime.fromisoformat('2021-02-23'))

# strptime() with an explicit format
x = datetime.strptime('2021-02-23T09:15:24+0200', "%Y-%m-%dT%H:%M:%S%z")
print('DateTime object with ISO date:', x)Code language: Python (python)

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 a datetime object.
  • Then call its timestamp() method to get the timestamp (seconds since 1 January 1970 UTC).

Example:

from datetime import datetime, timezone

date_str = "23/02/2012 09:30:23"
dt = datetime.strptime(date_str, "%d/%m/%Y %H:%M:%S")

# treat the time as UTC so the result is the same on every computer
ts = dt.replace(tzinfo=timezone.utc).timestamp()
print("Timestamp:", ts)Code language: Python (python)

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)
from dateutil import parser

for s in ['2021-02-23 09:15', 'Feb 23 2021 9:15 PM', '23 February 2021',
          'Tuesday, 23 Feb 2021', '2021-02-23T09:15:24+05:30']:
    print(repr(s), '->', parser.parse(s))Code 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:

from dateutil import parser

print(parser.parse('03/04/2021'))
print(parser.parse('03/04/2021', dayfirst=True))Code language: Python (python)

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 default argument to provide your own defaults.

You can also map timezone abbreviations to real timezones with the tzinfos argument:

from dateutil import parser, tz

tzinfos = {"BRST": -7200, "CST": tz.gettz("America/Chicago")}
x = parser.parse("2012-02-23 09:21:00 BRST", tzinfos=tzinfos)
print('DateTime:', x)
print(repr(x))Code language: Python (python)

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:

import arrow

birthday = '2012-02-23 09:15:45'
date = arrow.get(birthday, 'YYYY-MM-DD HH:mm:ss')
print(date)   # 2012-02-23T09:15:45+00:00Code language: Python (python)

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

TaskUse
String to datetime (known format)datetime.strptime(s, fmt)
String to datedatetime.strptime(s, fmt).date() or date.fromisoformat(s)
String to timedatetime.strptime(s, fmt).time()
ISO 8601 string to datetimedatetime.fromisoformat(s)
String to timestampdatetime.strptime(s, fmt).timestamp()
Unknown formatdateutil.parser.parse(s)

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

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python DateTime

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

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 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes
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

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview 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 a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

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

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

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
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com