Slicing and datetime module better here or any other alternative?

Hi guys,

I am doing a personal project and I hit a wall .Need some guidance.

Need to convert the below string to

Fri May 21 16:59:41 IST 2021

desired output : YYYY-MM-DD HH:mm:ss

I plan to do Slicing and then apply datetime is there a better alternative? (date time module to convert month name to numerical with 0 padded)

Also i saw that %m should be used for 0 padded number (05 in this case). But for some reason its not working when i try to convert it from alphabatical to numerical month

Any insight provided will help me .Beginner here.

Have a nice day stay safe. :sunny:


You could use the dateparser module to parse datetime objects from the string without having to splice it… It parses the time zone too…

Then you could use the strftime method of the datetime object to return a string in the required format…

And you’ll be done in 3 lines of code on your end because the extra modules do the heavy lifting :grin:

Hope that helps :slight_smile:

This is exactly what strftime() and strptime() are for. If you’re only working with IST time zone, then you can get away with hardcoding it:

from datetime import datetime
input_string = "Fri May 21 16:59:41 IST 2021"
input_format = "%a %b %d %X IST %Y"

output_date = datetime.strptime(input_string, input_format)
output_format = "%Y-%m-%d %X"
output_string = datetime.strftime(output_date, output_format)

But if not, then you’ll need a third party package like dateutil to interact with time zone names since datetime doesn’t have that built in (or use the dateparser library mentioned above).

Awesome thanks I will look into it. :slight_smile:

So we can specify a string and the pattern and it will automatically understand the parameters ? Thanks Andrew this feels a lot more simpler and straight forward that was
I was trying to do for the past 2 days.

That’s essentially what it does, yes.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.