Report this

What is the reason for this report?

How To Convert a String to a datetime Object in Python

Updated on June 2, 2026
Anish Singh Walia

By Anish Singh Walia

Sr Technical Content Strategist and Team Lead

How To Convert a String to a datetime Object in Python

Introduction

You turn a text timestamp into a datetime object with datetime.strptime() when the layout never changes. You use 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:00

strptime() gives you a datetime.datetime you compare, subtract, or pass to strftime(). When the text varies, install python-dateutil and call dateutil.parser.parse().

You will work through all three parsers, the main format codes, time zones, errors, and time.strptime() for legacy struct_time output.

Deploy your Python applications from GitHub using DigitalOcean App Platform. Let DigitalOcean focus on 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 on Python 3.11 and later.
  • dateutil.parser.parse(string) guesses the layout. Use this for user input, not million-row CSV jobs.
  • strftime() writes a string from a datetime. Remember: parse = strptime, format = strftime.
  • .date() and .time() drop the parts you do not need.
  • Wrong formats raise ValueError. Wrap imports in try/except or loop over format strings.
  • %z handles offsets like +0530. fromisoformat() handles +05:30 with the colon on Python 3.11+.
  • time.strptime() returns struct_time. Most apps should call datetime.strptime() instead.
  • Python 3.12 and 3.13 on Ubuntu 24.04 LTS keep these APIs unchanged. Start with the stdlib before you add packages.

Prerequisites

  • Python 3.8 or later. Python 3.11+ gives you the widest fromisoformat() support.

  • You know strings and the datetime module.

  • Optional: python-dateutil. Install with pip:

    pip install python-dateutil
    

Choose a parsing method

Method Format string required Dependency Timezone-aware Best for
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 or human-readable dates
time.strptime() Yes stdlib Limited Legacy C-style struct_time

Common strptime format directives

Directive Meaning Example input Parsed part
%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 zone name UTC name (platform-dependent)
%A / %a Weekday full / abbr Friday / Fri weekday
%B / %b Month full / abbr June / Jun month

See the full list in the strftime() and strptime() format codes docs.

Method 1: Parse with datetime.strptime()

datetime.strptime(date_string, format) matches your format codes to the string and returns a datetime object.

Parse a date and time 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:26

Parse to date or time 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:26

Parse 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 use %f (microseconds). Python pads with 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.123000

Method 2: Parse ISO strings with fromisoformat()

datetime.fromisoformat() reads many ISO 8601 strings with no manual format string. You see this shape in 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:30

Python version notes:

  • 3.7+: YYYY-MM-DD and basic T separators.
  • 3.11+: more ISO variants, including several timezone forms.
  • 3.6-3.10: smaller subset. Reach for dateutil.parser.parse() on odd strings.

Strings ending in Z mean UTC. On older Python, swap Z for +00:00 first:

s = "2024-06-15T10:30:00Z"
dt = datetime.fromisoformat(s.replace("Z", "+00:00"))

Method 3: Flexible parsing with dateutil

When each row 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 install python-dateutil first.

parse() costs more CPU on huge files because the library inspects each string. Stick with strptime() when every row shares one format.

Parse human-readable dates with a fixed format

You do not need dateutil for Jun 1 2005 1:33PM. Spell out 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:00

There is no space before %p because the input runs PM right after the minutes.

Parse strings with timezone offsets

Numeric offset with strptime() and %z. The offset has no 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-aware

ISO offset with a colon works on Python 3.11+ through fromisoformat():

from datetime import datetime

dt = datetime.fromisoformat("2024-06-15T10:30:00+05:30")

Named zones like America/New_York need zoneinfo (stdlib in Python 3.9+). Parse the naive local time, then attach the zone. Read How to Get the Current Date and Time in Python for worked examples.

Handle ValueError and multiple formats

Extra text or a wrong 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 data remains:  13:55:26

Loop over formats until one 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 raw string when a row fails. You fix bad data faster.

Convert datetime back to a string with strftime()

strftime() reverses strptime(). You go from object 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, 2024

Use this for yyyy-mm-dd filenames, SQL literals, or JSON fields.

Parse with time.strptime() (struct_time)

The time 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 when you need 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 date columns with Pandas

pandas.to_datetime() converts whole columns. Pass format like 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 in one column? Set errors="coerce" so bad rows become NaT instead of crashing the job. Start with the Pandas module tutorial if DataFrames are new to you.

Locale-specific month names

Non-English month names need 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, install the language pack or keep month names in English and match them with %B or %b.

Frequently asked questions

1. How do you convert a string to a datetime in Python?

You call datetime.strptime() with a format string:

from datetime import datetime

dt = datetime.strptime("2024-12-25", "%Y-%m-%d")

ISO timestamps go through datetime.fromisoformat("2024-12-25T10:30:00").

2. What does strptime() do?

strptime() means string parse time. You supply format codes (%Y, %m, %d, and others). Python returns a datetime. The time module version returns struct_time. Neither function guesses the layout.

3. What is strftime() in Python?

strftime() formats a datetime into a string. The codes match strptime(), but the direction flips. dt.strftime("%Y-%m-%d") prints 2024-06-15.

4. How do you use strptime() and strftime() together?

Parse, change the object, then 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-25

5. How do you convert a string to a timestamp in Python?

Parse first, then call .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 use UTC rules. For struct_time, use time.mktime() on the tuple from time.strptime() (local clock semantics).

6. How do you get a date instead of a datetime?

Parse, then call .date():

from datetime import datetime

d = datetime.strptime("12 25 2024", "%m %d %Y").date()
print(d)  # 2024-12-25

7. Is dateutil.parser.parse() slower than strptime()?

Yes on large uniform files. dateutil inspects every string. Fixed-format CSV and log columns run faster with strptime() or pandas.to_datetime(). See the Pandas module tutorial.

What’s next

You now have three paths: strptime() for fixed layouts, fromisoformat() for ISO API fields, and dateutil.parser when the text varies. Add time zone handling before production, wrap untrusted input in try/except, and reach for strftime() when you export strings again.

Keep going with Python tutorials, str() and repr() in Python, and the official datetime documentation.

Run timestamp pipelines on DigitalOcean App Platform without managing servers.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author

Anish Singh Walia
Anish Singh Walia
Author
Sr Technical Content Strategist and Team Lead
See author profile

I help Businesses scale with AI x SEO x (authentic) Content that revives traffic and keeps leads flowing | 3,000,000+ Average monthly readers on Medium | Sr Technical Writer(Team Lead) @ DigitalOcean | Ex-Cloud Consultant @ AMEX | Ex-Site Reliability Engineer(DevOps)@Nutanix

Still looking for an answer?

Was this helpful?

Hi Pankaj ! I need some help. I have a sample .CSV file from a Finger mark scanner to maintain attendance of employees. Can some one help me with a code to convert, Date, and other two Time columns to Date/Time in Pandas? I get an error. please see the attachment. https://colab.research.google.com/drive/1dnfigKSDoZsXiVIByWojXnkSgAEI6WOr Thank you !!! Indrajith - Sri Lanka 0772 078 441 / Mobile/Wtsapp

- Indrajith

In the datetime module, there is a function “datetime.datetime.today().weekday()”. This function returns the day of the week as an integer, where Monday is 0 and Sunday is 6. Please write a Python program using a for loop to generate and print log entries for the rest of the week starting from today. For example, if today is Wednesday, the program prints “Wednesday entry:”, “Thursday entry:”, “Friday entry:”, and “Saturday entry:” in separate lines. (Hint: the lower end of the range is today’s weekday and the upper end is 5 for Saturday).

- bhaigan

Thank you Sir! Found this arrticle very useful, when converting string data to dates in MongoDB documents!

- Victor Ochieng

Hi what about the day of the month, without 0-padding? 1,2,3,…,10,…30,31? In strftime it would be %-d, but that verbose doesn’t work when using to_datetime (string_to_convert_in_date, format=format_to_use) Any ideas? Thanks

- nono_london

Thank you for the post, very helpful examples

- Leo

Hello, Can you please let me know, how to compare 2 dates with $gte and $lte using python and mongodb ?

- RB

There is a mistake in this article. The ‘y’ in ‘%m/%d/%y’ will be capital. so the format will be ‘%m/%d/%Y’ i faced this problem this is the mistak in this article

- new

in string to datetime code line no 5 datetime_object = datetime.strptime(datetime_str, ‘%m/%d/%y %H:%M:%S’) must be datetime_object = datetime.datetime.strptime(datetime_str, ‘%m/%d/%Y %H:%M:%S’) 1. datetime itself a module which have no strptime attribute. 2. %y must be %Y. A format is a format which cannot be changed.

- Keshav wadhwa

Very crisp and informative.Try more like this.

- Yogesh

Hello Sir, How can we convert Tue AUG 11 02:30:18 UTC 2020? I tried from datetime import datetime datetime_object =“” datetime_str = “Tue Aug 11 01:40:27 UTC 2020” try: datetime_object = datetime.strptime(datetime_str, ‘%A %B %d %H:%M:%S %Z %Y’) print(type(datetime_object)) print(datetime_object) except ValueError as ve: print(‘ValueError Raised:’, ve) But it is not working.Can you please help?

- Tiny Jimmy

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Start building today

From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.

Dark mode is coming soon.