Sagar
Sagar

Reputation: 1175

Convert string to datetime object in python

I am running the below code

import datetime
d =datetime.datetime.strptime('2018-11-20T09:12:01.7511709Z', '%Y-%m-%d %H:%M:%S.%f')

I am getting an exception as

ValueError("time data '2018-11-20T09:12:01.7511709Z' does not match format '%Y-%m-%d %H:%M:%S.%f'",))

What is wrong with my code here. please help.

Upvotes: 1

Views: 811

Answers (4)

georgexsh
georgexsh

Reputation: 16624

%f directive accepts from one to six digits, try omit last two digits of your input:

datetime.datetime.strptime('2018-11-20T09:12:01.7511709Z'[:-2], '%Y-%m-%dT%H:%M:%S.%f')

Upvotes: 3

DatHydroGuy
DatHydroGuy

Reputation: 1116

Looks like you need to truncate your microseconds to 6 decimal places (documentation seems to support this: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior)

The following worked fine:

import datetime
d = datetime.datetime.strptime('2018-11-20T09:12:01.751171Z', '%Y-%m-%dT%H:%M:%S.%fZ')

If you want to correctly round your microseconds, try this:

import datetime


time_string = '2018-11-20T09:12:01.7511709Z'
date_time, microseconds = time_string.split('.')
microseconds = microseconds[:-1]
rounding = len(microseconds) - 6
divisor = 10 ** rounding
new_micros = int(round(int(microseconds) / divisor, 0))
time_string = date_time + '.' + str(new_micros) + 'Z'
d = datetime.datetime.strptime(time_string, '%Y-%m-%dT%H:%M:%S.%fZ')

Upvotes: 2

Also the easiest way:

from datetime import datetime
str(datetime.now())

'2018-11-20 14:58:05.329281'

Upvotes: 0

jpp
jpp

Reputation: 164773

You can use a 3rd party library such as dateutil, which performs the microsecond truncation (though not rounding):

from dateutil import parser

print(parser.parse('2018-11-20T09:12:01.7511709Z'))

datetime.datetime(2018, 11, 20, 9, 12, 1, 751170, tzinfo=tzutc())

Upvotes: 0

Related Questions