VOOZH about

URL: https://www.geeksforgeeks.org/python/how-to-convert-timestamp-string-to-datetime-object-in-python/

⇱ How to convert timestamp string to datetime object in Python? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to convert timestamp string to datetime object in Python?

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.


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.


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.


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.


Output
2023-07-21 10:30:45

Explanation: s holds a string in ISO format. datetime.fromisoformat(s) directly parses the string into a datetime object dt.

Related articles

Comment
Article Tags: