1

Hi I am trying to convert the following time format

2020-08-28T13:42:00.298363-05:00

to

28-Sept-2020

I am using the following code but it does not work.

from datetime import datetime
 
start_time = "2020-08-28T13:42:00.298363-05:00"
start_period_obj = datetime.strptime(start_time, "%Y-%m-%dT%H:%M:%f.%-s-%z)
    print(start_period_obj)

and the output is

File "time conveter.py", line 19
    start_period_obj = datetime.strptime(start_time, "%Y-%m-%dT%H:%M:%f.%-s-%z)
                                                                              ^
SyntaxError: EOL while scanning string literal

2 Answers2

0

Your code is missing the closing quote at the end of the datetime format string, which is causing the error message you see. You also have an issue with the actual format string as well, as pointed out by @ChrisCharley

This start_period_obj = datetime.strptime(start_time, "%Y-%m-%dT%H:%M:%f.%-s-%z)

Should be start_period_obj = datetime.strptime(start_time, "%Y-%m-%dT%H:%M:%S.%f%z")

To then generate your desired format you can use:

start_period_obj.strftime("%d-%b-%Y")

See here for full details https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

Query Stash
  • 149
  • 5
0

Try this:

from datetime import datetime
 
start_time = "2020-08-28T13:42:00.298363-05:00"

#removing the time information since, you don't want in the final output anyway
start_time  = start_time.split('T')[0]
start_period_obj = datetime.strptime(start_time, "%Y-%m-%d")
start_period_obj = start_period_obj.strftime("%d-%b-%Y")
print(start_period_obj)

Or this one liner:

start_period_obj = datetime.strptime(start_time.split('T')[0], "%Y-%m-%d").strftime("%d-%b-%Y")
print(start_period_obj)

Output:

'28-Aug-2020'
Grayrigel
  • 3,474
  • 5
  • 14
  • 32
  • 1
    this is a one-liner (Python 3.7)... `datetime.fromisoformat("2020-08-28T13:42:00.298363-05:00").strftime("%d-%b-%Y")` – FObersteiner Sep 29 '20 at 06:44
  • Thanks. well, I didn't know about it. Added one line solution using `strptime` and `strftime` probably slower but works. – Grayrigel Sep 29 '20 at 07:56
  • 1
    ok my comment might have been misleading, I didn't mean to propose a one-liner for it being a one-liner ;-) `fromisoformat` is more readable in my opinion and [very efficient](https://stackoverflow.com/questions/13468126/a-faster-strptime). – FObersteiner Sep 29 '20 at 07:58
  • 1
    I understand you didn't mean to propose one line solution. It is just that I got random dislikes for posting this solution and I can't figure out why. So, I figured it could one line people. I agree `fromisoformat` clearly is much more readable is a much better option. Thanks. – Grayrigel Sep 29 '20 at 08:08
  • well, better not to think too much about getting downvotes. The other way around, I don't allow myself to downvote without leaving a comment. In this case, I just left the comment ^^ – FObersteiner Sep 29 '20 at 08:21