Movatterモバイル変換


[0]ホーム

URL:


Open In App

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
fromdatetimeimportdatetimes="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 objectdt.

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
importpandasaspds="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: sholds 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 moduleprovides powerful parsing without specifying the format.

Python
fromdateutilimportparsers="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
fromdatetimeimportdatetimes="2023-07-21 10:30:45"dt=datetime.fromisoformat(s)print(dt)

Output
2023-07-21 10:30:45

Explanation: sholds a string in ISO format.datetime.fromisoformat(s)directly parses the string into a datetime objectdt.

Related articles


Improve
Improve
Article Tags :

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp