How to convert timestamp string to datetime object in Python? (original) (raw)

Last Updated : 23 Aug, 2025

To convert a timestamp string to a datetime object in Python, we parse the string into a format Python understands. This allows for easier date/time manipulation, comparison and formatting. **For example, the string "2023-07-21 10:30:45" is converted into a datetime object representing that exact date and time.

Let’s explore simple and efficient ways to do this.

Using datetime.strptime()

**datetime.strptime() is the most common way to convert a date-time string into a datetime object. You provide the string and its format.

Python `

from datetime import datetime s = "2023-07-21 10:30:45" dt = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")

print(dt)

`

Output

2023-07-21 10:30:45

**Explanation: s holds the timestamp string. We use strptime() with the format "%Y-%m-%d %H:%M:%S" to parse it into a datetime object **dt.

Using pandas.to_datetime()

**pandas.to_datetime() is powerful for working with large datasets or performing operations in dataframes, but can also be used for single string conversion.

Python `

import pandas as pd s = "2023-07-21 10:30:45" dt = pd.to_datetime(s, format="%Y-%m-%d %H:%M:%S")

print(dt)

`

Output

2023-07-21 10:30:45

**Explanation: s holds the timestamp string. **pd.to_datetime() converts it directly into a pandas Timestamp object, which behaves like a datetime object.

Using dateutil.parser.parse()

The dateutil module provides powerful parsing without specifying the format.

Python `

from dateutil import parser

s = "2023-07-21 10:30:45" dt = parser.parse(s)

print(dt)

`

Output

2023-07-21 10:30:45

**Explanation: s is parsed automatically by parser.parse(), which intelligently detects the format and returns a datetime object.

Using datetime.fromisoformat()

If the timestamp string is in ISO 8601 format (i.e., "YYYY-MM-DD HH:MM:SS"), **fromisoformat() is the cleanest and most efficient method to convert it to a datetime object.

Python `

from datetime import datetime

s = "2023-07-21 10:30:45" dt = datetime.fromisoformat(s)

print(dt)

`