1

I have this time here : 2017-08-05T05:21:10.6582942Z
And I want to convert it into %Y-%m-%d %H:%M:%S
I can do that using some funky methods such as :

date = "2017-08-05T05:21:10.6582942Z"
new_date = date[:11] + " " + date[12:][:-9]

But is there any way I can do something cleaner with datetime or some libraries made for this specific purpose ?

2
  • datetime.strptime(…).strftime(…)…? Commented Nov 7, 2022 at 9:09
  • To parse more than 6 digits of fractional seconds "automatically", dateutil's parser could be an option. Note however that Python's datetime is limited to microsecond precision, so those additional digits will be ignored. You'd have to use a third-party library to consider them. Commented Nov 7, 2022 at 10:10

2 Answers 2

1

Using the datetime library with the strptime method (for parsing) and the strftime method (for formatting), this can be accomplished with no splits and limited slicing as:

from datetime import datetime as dt

date = '2017-08-05T05:21:10.6582942Z'
output = dt.strptime(date[:-2], '%Y-%m-%dT%H:%M:%S.%f').strftime('%Y-%m-%d %H:%M:%S')

Output:

'2017-08-05 05:21:10'

Note: The slice is needed to remove the last two characters from the string date, as the %f (fractional seconds) formatter only accepts six decimal values, and your string contains seven decimal values.

Per the formatting documentation:

%f: Microsecond as a decimal number, zero-padded to 6 digits.

Sign up to request clarification or add additional context in comments.

Comments

0

Start with importing datetime:

import datetime as dt

Convert string to datetime object:

date = "2017-08-05T05:21:10.6582942Z"
new_date = dt.datetime.strptime(date[:-2], "%Y-%m-%dT%H:%M:%S.%f") # -2 slice to since %f only accepts 6 digits.

Format datetime object as string:

format_date = dt.datetime.strftime(new_date, "%Y-%m-%d %H:%M:%S") # returns your format

However, looking at your code it feels your date is already formatted and you don't require the last .strftime() usage.

5 Comments

If you process the string like that, why not simply replace the T with a space ?
Well, .strptime() cannot forge inputs and takes everything passed. stackoverflow.com/questions/29284850/…
@FObersteiner here the motive is to make them understand .strftime() and .strptime() rather than just giving a solution.
I think that's a good answer, but I was wondering if I can do that without parsing it by hand. I don't want to create a datetime object of something I've already parsed before. I want datetime to parse it for me (because this is a simple example, but I have more complexe time to parse and I don't want to make some mistakes by parsing it myself)
Checked the revised answer @Vincent.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.