duckman
duckman

Reputation: 747

read in string as datetime object with 3 digits for millisecond

I am reading in a string that is in a datetime format. However, instead of having 6 digits for the millisecond, it has only 3 with a letter Z at the end. How do I read in this string and make it a datetime object, and add 1 day, and write out this as a string in the above format i.e. 3 digits for the millisecond and a letter Z at the end. I tried the following code but not successful:

old_date= "2018-06-06T23:59:59.999Z"
new_date = datetime.datetime.strptime(old_date, '%Y-%m-%d %H:%M:%S.%f%Z') + datetime.timedelta(days=1)
print(new_date)

Upvotes: 6

Views: 8731

Answers (1)

BENY
BENY

Reputation: 323366

You should using this format

datetime.datetime.strptime(old_date, '%Y-%m-%dT%H:%M:%S.%fZ')
Out[180]: datetime.datetime(2018, 6, 6, 23, 59, 59, 999000)

Update

dt1=datetime.datetime.strptime(old_date, '%Y-%m-%dT%H:%M:%S.%fZ')+datetime.timedelta(days=1)
dt1.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]+'Z'
Out[196]: '2018-06-07 23:59:59.999Z'

Upvotes: 4

Related Questions