How to convert String to datetime in python

In this post, we will see how to convert String to datetime object in python.
You can simply import datetime module and use strptime method to convert String to datetime object.

from datetime import datetime datetimeObj = datetime.strptime('Nov 10 2017 3:29PM', '%b %d %Y %I:%M%p') print(datetimeObj) print ('Year:', datetimeObj.year) print ('Mon :', datetimeObj.month) print ('Day :', datetimeObj.day)

Output:

2017-11-10 15:29:00
Year: 2017
Mon : 11
Day : 10

You can do it using time module too.

import time t=time.strptime('Nov 10 2017 3:29PM', '%b %d %Y %I:%M%p') print(t)

Output:

time.struct_time(tm_year=2017, tm_mon=11, tm_mday=10, tm_hour=15, tm_min=29, tm_sec=0, tm_wday=4, tm_yday=314, tm_isdst=-1)

That’s all about How to convert String to datetime object.

Leave a Reply

Your email address will not be published. Required fields are marked *