Python Forum
string to date time- suggestion required - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: string to date time- suggestion required (/thread-12252.html)



string to date time- suggestion required - anna - Aug-16-2018

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



RE: string to date time- suggestion required - Gribouillis - Aug-16-2018

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'



RE: string to date time- suggestion required - buran - Aug-17-2018

>>> 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?


RE: string to date time- suggestion required - Gribouillis - Aug-17-2018

(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.


RE: string to date time- suggestion required - buran - Aug-17-2018

(Aug-17-2018, 07:34 AM)Gribouillis Wrote: MICROseconds
yes, you are right - microseconds. my bad.
IMHO fractional part is seconds is quite obvious.