Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add trailing zeroes to datetime as string?

What's an easy way to modify the following timestamps (as strings) like this:

2020-11-04T19:48:19.9 --> 2020-11-04T19:48:19.90
2020-11-04T19:48:20 --> 2020-11-04T19:48:20.00

A bit of background: I have timestamps coming from an API that typically look like this:

2020-11-04T19:48:19.87

I want to convert them to datetime, which can be done with the datetime module:

my_ts = datetime.datetime.strptime(my_ts, '%Y-%m-%dT%H:%M:%S.%f')

Now %f expects 6 digits, which is easily achieved by:

my_ts = my_ts + '0000' 

However, for my data the fraction-bit may be missing a trailing zero, or missing altogether, like this:

2020-11-04T19:48:19.9
2020-11-04T19:48:20

What's an easy way to achieve this?

What I currently do is this:

teststring = "2020-11-04T19:48:19"

if '.' not in teststring:
    fraction_length = 0
else:
    fraction_length = len(teststring.split(".",1)[1])

if fraction_length == 0:
    new_teststring = teststring + '.00'
elif fraction_length == 1:
    new_teststring = teststring + '0'
else:
    new_teststring = teststring

This appears to be unnecessarily complicated. There has to be a better way, doesn't it?

Any hints are greatly appreciated.

like image 535
Sebastian Avatar asked Oct 14 '25 20:10

Sebastian


1 Answers

try using the dateutil library

as an example:

from dateutil import parser
dt1 = ['2020-11-04T19:48:19.9', '2020-11-04T19:48:20', '2020-11-04T19:48', '2020-11-04T19:48:20.01']

for dt in dt1:
    print(parser.parse(dt))

yields:

2020-11-04 19:48:19.900000
2020-11-04 19:48:20
2020-11-04 19:48:00
2020-11-04 19:48:20.010000
like image 141
itprorh66 Avatar answered Oct 17 '25 08:10

itprorh66



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!