1

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.

1
  • The date comes to me as a variable which has T and Z. Its dynamic value for me. Is there a way i can convert this Commented Nov 20, 2018 at 9:47

4 Answers 4

3

%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')
Sign up to request clarification or add additional context in comments.

Comments

2

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')

2 Comments

your code works but you have changed the time little bit - '2018-11-20T09:12:01.7511709Z' is my time to covert. i think i may have to truncate to make this work
I have updated the answer to extract the microseconds, correctly round them, and the re-insert them into your format string.
0

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())

Comments

0

Also the easiest way:

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.