Python Forum

Full Version: string to date time- suggestion required
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi All,

I am getting time as in this format '20180801194918.0', I want convert this to date time format.

below in the my code, but need suggestion

a = "20180801194918.0"
        year = a[:4]
        month = a[4:][:2]
        date = a[6:][:2]
        hours = a[8:][:2]
        mins = a[10:][:2]
        seconds = a[12:][:2]
        datetimes = year+"-"+month+"-"+date+" "+hours+":"+mins+":"+seconds
        print(datetimes)
Output:
2018-08-01 19:49:18
Use built-in tools
>>> import datetime as dt
>>> t = dt.datetime.strptime('20180801194918.0'.split('.')[0], '%Y%m%d%H%M%S')
>>> str(t)
'2018-08-01 19:49:18'
>>> import datetime as dt
>>> t = dt.datetime.strptime('20180801194918.0', '%Y%m%d%H%M%S.%f')
>>> str(t)
'2018-08-01 19:49:18'
>>>
why ignore the milliseconds?
(Aug-17-2018, 06:25 AM)buran Wrote: [ -> ]why ignore the milliseconds?
The interpretation of the fractional part in the original format is far from obvious. Note that %f parses MICROseconds on 6 digits if I understand it well.
(Aug-17-2018, 07:34 AM)Gribouillis Wrote: [ -> ]MICROseconds
yes, you are right - microseconds. my bad.
IMHO fractional part is seconds is quite obvious.