惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Stack Overflow Blog
Stack Overflow Blog
L
LangChain Blog
人人都是产品经理
人人都是产品经理
酷 壳 – CoolShell
酷 壳 – CoolShell
T
Tailwind CSS Blog
N
Netflix TechBlog - Medium
Microsoft Security Blog
Microsoft Security Blog
J
Java Code Geeks
博客园 - 【当耐特】
量子位
有赞技术团队
有赞技术团队
Jina AI
Jina AI
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园_首页
C
Check Point Blog
B
Blog RSS Feed
M
MIT News - Artificial intelligence
H
Help Net Security
雷峰网
雷峰网
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 聂微东
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
A
About on SuperTechFans
腾讯CDC

DigitalOcean Community Tutorials

It's Time to Break Up with Your Cloud: Why AI Teams are Switching We Built a Private-Document AI App to Test Platform Security. Here Is What We Could Actually Verify. PostgreSQL Explained: A Complete Beginner-to-Advanced Guide How To Install and Configure Postfix on Ubuntu How To Build a Web Application Using Flask in Python 3 Build AI Reading List with DigitalOcean Functions and Mistral How To Concatenate Strings in Python How to Allow MySQL Remote Access Securely How To Install and Use Docker on Rocky Linux How To Build a Multi-Agent AI System with Docker Agent DSPy Use Cases: Build Optimized LLM Pipelines How To Submit AJAX Forms with jQuery Build an AI-Powered GPU Fleet Optimizer with the DigitalOcean AI Platform ADK Monitor GPU Utilization in Real Time: A Complete Guide Reduce File Size of Images in Linux - CLI and GUI methods Reduce PDF File Size in Linux: Tools and Methods How To Set Up a Private Docker Registry on Ubuntu How To Troubleshoot Terraform: Errors and Fixes How to Use Go Modules Python Multiprocessing Example: Process, Pool & Queue Convert Class Components to Functional Components with React Hooks How To Install and Configure Ansible on Ubuntu LLM Tokenizers Simplified: BPE, SentencePiece, and More How To Monitor System Authentication Logs on Ubuntu How to Use Traceroute and MTR to Diagnose Network Issues How to Deploy Postgres to Kubernetes Cluster Importing Packages in Go: A Complete Guide Create RAID Arrays with mdadm on Ubuntu How To Make an HTTP Server in Go How To Set Up Time Synchronization on Ubuntu
How To Convert a String to a datetime Object in Python
Anish Singh Walia · 2022-08-04 · via DigitalOcean Community Tutorials

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.

Still looking for an answer?

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.