Python Forum
string to date time- suggestion required
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
string to date time- suggestion required
#1
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
Reply
#2
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'
Reply
#3
>>> 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?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
(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.
Reply
#5
(Aug-17-2018, 07:34 AM)Gribouillis Wrote: MICROseconds
yes, you are right - microseconds. my bad.
IMHO fractional part is seconds is quite obvious.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Suggestion on how to speed up this code? sawtooth500 1 222 May-04-2024, 07:13 PM
Last Post: sawtooth500
  Compare current date on calendar with date format file name Fioravanti 1 293 Mar-26-2024, 08:23 AM
Last Post: Pedroski55
  Date Time Series Help...Please spra8560 2 416 Feb-01-2024, 01:38 PM
Last Post: spra8560
  Python date format changes to date & time 1418 4 688 Jan-20-2024, 04:45 AM
Last Post: 1418
  Downloading time zone aware files, getting wrong files(by date))s tester_V 9 1,103 Jul-23-2023, 08:32 AM
Last Post: deanhystad
  Formatting a date time string read from a csv file DosAtPython 5 1,395 Jun-19-2023, 02:12 PM
Last Post: DosAtPython
  Wait til a date and time KatManDEW 2 1,462 Mar-11-2022, 08:05 PM
Last Post: KatManDEW
  Date format and past date check function Turtle 5 4,356 Oct-22-2021, 09:45 PM
Last Post: deanhystad
  Can you give me some suggestion about PCEP Newbie1114 0 1,043 Oct-14-2021, 03:02 PM
Last Post: Newbie1114
  instagram followers name without suggestion for you jacklee26 1 3,208 Oct-02-2021, 04:57 AM
Last Post: ndc85430

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020