How to Convert a String into DateTime in Python | AlixaProdev

convert string into date time objects

We can convert a String into Datetime in Python in many ways. We can do so if we have a string Nicely Formatted in the Date Format, but most of the time it is not the case and we got some problems when we are doing so. In this Tech Article, I am going to show you different possible methods that can be used to convert a string into DateTime in the Python Programming language. 

Suppose we have a list of date formatted strings and we want to convert it into DateTime to do calculations on and use them further in our python programming project. look at the following example
serial                            date
1                                    Jan 1, 2003, 3:12PM
2                                    Sep 4, 2013, 1:34Am

Now in the above case, we want to change them to the DateTime object so what would be the solution?
There are many ways to convert a string into DateTime in python and some of them are given below.

1.Converting a String to DateTime in Python with datetime.strptime:-

strptime() is a method present in the datetime module in python. which on importing can give us the easiest and simplest way to convert string Date into python datetime Object. this method can handle a lot of formats and the format can be specified by you as it will take two arguments one is the string Date and the other is the pattern or format of the date that you are using it. 


from datetime import datetime as formater
datetime_object = formater.strptime('Jan 6 2021  5:44PM', '%b %d %Y %I:%M%p')
print(datetime_object)

>The output of the above code will be a date which you can see in the following picture.

converting a string into date

2. Converting a String to datetime by using dateutil in Python:-

To convert a string into Date in the python programming language we can use another method. In this method we will be installing a third party do not worry it is just a python package "dateutil
we can install it by using pip on a terminal as follows.


pip install python-dateutil

after installing the dateutil we can use it as follows.


from dateutil import parser
f=parser.parse("Jan 28 2020 12:00AM")
print(f)

# Input : 'Jan 28 2020 12:00AM'
# Output : '2020-01-28 00:00:00'


I like this one more than the strptime() is this one can guess the format as well like in the previous one we should have specify the format as well but this utility is really helpful in this way.  Be aware that for large data amounts this might not be the most optimal way to approach the problem. Guessing the format every single time may be horribly slow.

Converting a string date into datetime in python

3. Convert YYYY-MM-DD string to datetime object in Python

Sometimes we have a raw string format of date like thisYYYY-MM-DD. we can easily convert this type of string date into datetime object. The following code explain how we can acheive the results.


from datetime import datetime

# fomat = YYYY-MM-DD
date_string = "2021-06-30 10:10:10"
print(datetime.fromisoformat(date_string))

# output: 2021-06-30 10:10:10

4. Using Pandas to Convert String to datetime object in Python

This is another useful way to convert a string into dates below is the example which will help you understnad how we can convert a string into a datetime with pandas python.




import pandas as pd

dates = ['2021-10-15', '2022-10-16']

dates_1 = [d.date() for d in pd.to_datetime(dates)]
for date in dates_1:
    print(date)


dates_2 =pd.DatetimeIndex(dates).date.tolist()
for date in dates_2:
    print(date)
# output is following    
2021-10-15
2022-10-16
2021-10-15
2022-10-16

5. The Fastest way to convert a String into datetime Object in Python:-

Now sometimes speed does matter when we have a lot of data to process in this case we can use the following method to convert the string date into datetime object in the easiest and the fastest way. We will again use pandas python to acheive the result.


import pandas as pd 

N = 1000

l = ['Jun 1 2005  1:33PM'] * N

list(pd.to_datetime(l, format=format))

%timeit _ = list(pd.to_datetime(l, format=format))
1.58 ms ± 21.6 ┬Ás per loop (mean ± std. dev. of 7 runs, 1000 loops each)


Summary and Conclusion:-

There are many ways through which we can convert a raw string into datetime as mentioned above. Pick the one which best suit you. To learn more about DateTime package you can have a look on this article and if you want to learn python programming you can visit my youtube channel [CodeWithAli].

AlixaProDev

I’m Ali, Founder of alixaprodev.com. I am a Software developer, and I love to write articles to help students, developers, and learners. I started alixaprodev.com because of my love for Python, Java, and WebDev.

Post a Comment (0)
Previous Post Next Post