In this post, we are going to learn about how to convert string to datetime in Python. Like other programming languages, Python does not have Date as a built-in datatype. But the DateTime module is used to manipulate Date and time by using the classes like Date, Time, and DateTime.
1. Python Convert string to datetime object
The datetime module strptime() function is used to convert a string to a datetime object. It returns a struct_time and defualt string format is “%a %b %d %H:%M:%S %Y”.
Syntax
datetime.strptime(string_date,format_code)
Parameters
- string_date : The string we need to convert into a datetime object.
- Format_code: The format in which we want to convert a string date to a datetime object.
strptime() to convert string to datetime object
#Python Program of How to convert string to datetime in Python
from datetime import datetime
Str_dateTime = '23/07/21 08:59:26'
dt_obj = datetime.strptime(Str_dateTime, '%d/%m/%y %H:%M:%S')
print(dt_obj)
print(dt_obj.time())
print(dt_obj.date())
print('Type:',type(dt_obj))
Output
2021-07-23 08:20:26
08:20:26
2021-07-23
Type: <class 'datetime.datetime'>
ValueError raised by strptime() method
If the string_date(date as string) is not as per the format_code then it will raise a valueError.In this example the string as date( Str_dateTime = ’07/23/21 08:59:26′) is in “%m%d%y %H:%M:%S” format but the format_code is %d/%m/%y %H:%M:%S” that is why raising value error.
Example ValueError raised by DateTime
from datetime import datetime
Str_dateTime = '07/23/21 08:59:26'
dt_obj = datetime.strptime(Str_dateTime, '%d/%m/%y %H:%M:%S')
print(dt_obj)
print('Type:',type(dt_obj))
Output
ValueError: time data '07/23/21 08:59:26' does not match format '%d/%m/%y %H:%M:%S'
- 6 ways to get current Timestamp in Python
- How to convert DateTime to string in Python
- How to convert string to datetime in Python
- Unix Timestamp to datetime in Python
2. Python Convert string convert string to datetime
In this example, we are converting string date only to date object by using the strptime() along with the date() method, then we are Printing the resulted date object using the print(date_obj).
Example Convert string to date object
from datetime import datetime
Date_string = "07/25/2121"
date_obj = datetime.strptime(Date_string,"%m/%d/%Y").date()
print(date_obj)
Output
2121-07-25 tyep : <class 'datetime.date'>
3.Convert string to time object
In this example, we are using the strptime() along with the time() method of the datetime module. We are converting string time to time object in the format ‘%H::%M::%S’.
Example to Convert string to time object
#Python Program of How to convert string to datetime in Python
from datetime import datetime
time = '12::50::40'
t_obj = datetime.strptime(time, '%H::%M::%S').time()
print(t_obj)
print(type(t_obj))
Output
12:50:40
<class 'datetime.time'>
4.Time Module to convert string to time object
The Python’s time module strptime() function converts a string time to struct_Time that it returns by localtime(), gmtime() function.
time.strftime(format_code[,time])
Parameters
- time: The time that needs to be converted.
- Format_code: This is a string format in which we have to convert a given time.
Example to convert string to time object
import time
time_val_str = "03::47::20"
t_obj = time.strptime(time_val_str, '%H::%M::%S')
print("type:",type(t_obj))
print(t_obj)
print("\n")
print("hh::mm::ss =",t_obj.tm_hour,'::',t_obj.tm_min,'::',t_obj.tm_sec)
Output
type: <class 'time.struct_time'>
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=3, tm_min=47, tm_sec=20, tm_wday=0, tm_yday=1, tm_isdst=-1)
hh::mm::ss 3 :: 47 :: 20
5. Convert string to Timestamp
In this example, we are converting string date to dateobject(dt_obj) by using the datetime module’s strptime() method.Finally converting dateobject(dt_obj) to timestamp using timestamp() method.
Program to convert string datetime to Timestamp
from datetime import datetime
date_str = "07/25/2121 12:30:20"
dt_obj = datetime.strptime(date_str,"%m/%d/%Y %H:%M:%S")
timestamp = datetime.timestamp(dt_obj)
print(timestamp)
Output
4782870020.0
6.Convert string to datetime in Python Pandas
- In this example, we are using the Python pandas library to convert string to datetime using the to_datetime() method.
- To use Pandas library first need to import it using the import pandas as pd
- Printing the result using the print(pd.to_datetime(dt_obj)). It is printing the datatype dtype=’datetime64[ns]’ and datetime object.
Example to Convert string to datetime in Python Pandas
import pandas as pd
dt_obj = ['07-25-2021 10:40:00 PM']
print(pd.to_datetime(dt_obj))
Output
DatetimeIndex(['2021-07-25 22:40:00'], dtype='datetime64[ns]', freq=None)
7. Convert string to datetime UTC
- Here we are converting string datetime to UTC. To get timezone information We have imported module pytz . We have a timezone for pytz.timezone (‘America/New_York’).
- Converting the string to a datetime object using strptime().
- Finally converting the dt_local_tz to UTC using this code dt_local_tz.astimezone(pytz.utc).
Example to Convert string to datetime UTC
import pytz
from datetime import datetime
timezone_NY = pytz.timezone ('America/New_York')
dt_obj = datetime.strptime("25/07/2021 11:15:15" ,"%d/%m/%Y %H:%M:%S")
dt_local_tz = timezone_NY.localize(dt_obj)
print(dt_local_tz.tzinfo)
Dt_utc = dt_local_tz.astimezone(pytz.utc)
print(Dt_utc)
Output
America/New_York
2021-07-25 15:15:15+00:00
8. Convert string to datetime to different Timezone
In this example, we are learning about how to convert string to datetime with timezone. We are converting the timezone_NY to tz_london By using the astimezone() method of pytz module. The pytz module is used to get timezone information.
Example to Convert string to timezone
import pytz
from datetime import datetime
timezone_NY = pytz.timezone ('America/New_York')
tz_london = pytz.timezone('Europe/London')
dt_NY = datetime.strptime("25/07/2021 09:15:15" ,"%d/%m/%Y %H:%M:%S")
dt_local_tz = timezone_NY.localize(dt_NY)
#converting timezone to london
london_dt_obj = dt_local_tz.astimezone(tz_london)
print(london_dt_obj.tzinfo)
Output
2021-07-25 14:15:15+01:00
Europe/London
9. Convert string to datetime by dateutil libraray
In this example, we are using the dateutil library to convert string to date object.
from dateutil.parser import parse
dt_obj = parse('2021-07-25 23:40:14')
print(dt_obj)
print(type(dt_obj))
Output
2021-07-25 23:40:14
<class 'datetime.datetime'>
10. Convert list of string to datetime object
In this example, we have a list of strings with the different formats, then by using the dateutil library we are converting all at once to a datetime object.
Example for list of string to datetime
from dateutil.parser import parse
from dateutil.parser import parse
list_date_str = [
'2021-07-25 08:20:27.233560',
'July 28 2021 8:40PM',
'July 25 2021 at 8:40PM',
'October 29, 2020, 23:20:56'
]
for str in list_date_str:
#string to datetobject
dt_obj = parse(str)
print(dt_obj.date())
print(dt_obj.time())
print(dt_obj.tzinfo,'\n')
Output
2021-07-25
08:20:27.233560
None
2021-07-28
20:40:00
None
2021-07-25
20:40:00
None
2020-10-29
23:20:56
None
Summary
In this post we have learned how to convert string to datetime in Python using strptime(), Convert a list of strings with the different formats with examples.