Home > Software design >  How to trim time string to specific format?
How to trim time string to specific format?

Time:06-15

I have a string that represents datetime but it has 9 digit numbers microseconds instead of 6.

'2022-05-09 08:02:18.106869456  0000 UTC'

I'm looking for the best way to trim those 3 digits from the string in order to convert it to datetime object.

CodePudding user response:

Are you okay with lower precision?

Apply simple string operation to get rid of 3 extra digits and pass it to datetime.datetime.strptime.

import datetime
t = '2022-05-09 08:02:18.106869456  0000 UTC'
t2 = t[:26]   t[29:]  # made some assumptions about time string format
datetime.datetime.strptime(t2, '%Y-%m-%d %H:%M:%S.%f %z %Z')
# expected output: datetime.datetime(2022, 5, 9, 8, 2, 18, 106869, tzinfo=datetime.timezone(datetime.timedelta(0), 'UTC'))

CodePudding user response:

Pro You can use Regex to split each part of the string using this regex

import re 
regex = r"""(?P<year>[0-9]{4})-(?P<month>[0-9]{2})-(?P<day>[0-9]{2})\s(?P<hour>[0-9]{2}):(?P<min>[0-9]{2}):(?P<sec>[0-9]{2}).(?P<micro>\d*)\s(?P<diff>[\ \-]\d )\s(?
P<time_zone>\w )"""

d = re.search(regex,'2022-05-09 08:02:18.106869456  0000 UTC').groupdict()
print(d)

Then You can take what you want from the string

print:

{'year': '2022', 'month': '05', 'day': '09', 'hour': '08', 'min': '02', 
'sec': '18', 'micro': '106869456', 'diff': ' 0000', 'time_zone': 'UTC'}
  • Related