How to convert string into datetime format?
To convert a string into a datetime format, you can use the datetime.strptime
method, which parses an input string according to the specified format and returns a timezone-naive datetime object. Here’s an example:
from datetime import datetime
datetime_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
print(datetime_object) # Output: 2005-06-01 13:33:00
If you need a date object from a datetime object, you can use the .date()
method:
date_object = datetime.strptime('Jun 1 2005', '%b %d %Y').date()
print(date_object) # Output: 2005-06-01
Useful Links:
- strptime documentation: Python 2, Python 3
- strptime/strftime format string documentation: Python 2, Python 3
- Format string cheatsheet
Notes:
-
strptime
stands for “string parse time” -
strftime
stands for “string format time”
The other approach to convert string to date is by using the dateutil library, which provides a powerful way to parse strings into datetime objects without needing a specific format string. Here’s how you can use it:
from dateutil.parser import parse
datetime_object = parse('Jun 1 2005 1:33PM')
print(datetime_object) # Output: 2005-06-01 13:33:00
To obtain just the date from the parsed datetime object:
date_only = parse('Jun 1 2005').date()
print(date_only) # Output: 2005-06-01
You can use pandas.to_datetime
The pandas library offers a convenient to_datetime function that can also convert strings to datetime objects:
import pandas as pd
datetime_object = pd.to_datetime('Jun 1 2005 1:33PM')
print(datetime_object) # Output: 2005-06-01 13:33:00
To extract the date from the datetime object:
date_only = pd.to_datetime('Jun 1 2005').date()
print(date_only) # Output: 2005-06-01
Useful Links:
dateutil.parser documentation ( parser — dateutil 3.9.0 documentation) pandas.to_datetime documentation ( pandas.to_datetime — pandas 2.2.3 documentation)
Notes:
dateutil.parser.parse is useful for parsing a variety of date formats automatically. pandas.to_datetime is versatile and handles many date formats, also providing additional functionality for handling date-related data.