Quantcast
Channel: Convert string "Jun 1 2005 1:33PM" into datetime - Stack Overflow
Viewing all articles
Browse latest Browse all 55

Answer by officialrahulmandal for Converting string into datetime

$
0
0

If you don't want to explicitly specify which format your string is in with respect to date time format you can use this hack to by pass that step :-

from dateutil.parser import parse# function that'll guess the format and convert it into python datetime formatdef update_event(start_datetime=None, end_datetime=None, description=None):    if start_datetime is not None:        new_start_time = parse(start_datetime)        return new_start_time#sample input dates in different formatd = ['06/07/2021 06:40:23.277000','06/07/2021 06:40','06/07/2021']new = [update_event(i) for i in d]for date in new:    print(date)    # sample output dates in python datetime object    # 2014-04-23 00:00:00    # 2013-04-24 00:00:00    # 2014-04-25 00:00:00

If you want to convert it into some other datetime format just modify the last line with the format you like for example something like date.strftime('%Y/%m/%d %H:%M:%S.%f') :-

from dateutil.parser import parsedef update_event(start_datetime=None, end_datetime=None, description=None):    if start_datetime is not None:        new_start_time = parse(start_datetime)        return new_start_time#sample input dates in different formatd = ['06/07/2021 06:40:23.277000','06/07/2021 06:40','06/07/2021']# passing the dates one by one through the functionnew = [update_event(i) for i in d]for date in new:    print(date.strftime('%Y/%m/%d %H:%M:%S.%f'))    # sample output dates in required python datetime object    #2021/06/07 06:40:23.277000    #2021/06/07 06:40:00.000000    #2021/06/07 00:00:00.000000

try running the above sniipet to have a btter clarity. Thanks


Viewing all articles
Browse latest Browse all 55

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>