0

I have three unique date formats, listed below

date1 = "2018-05-31 14:34:42+00:00"
date2 = "2018-05-21T14:49:52.833"
date3 = "2018-06-01 00:00:00"

How can I convert into single date format("%Y-%m-%d %H:%M:%S") of all these three dates using python?

Tried the below code but I'm getting ValueError and TypeError's

from dateutil.parser import parse
def parse_date(request_date):
    request_date = parse(request_date)
    parsed_date = request_date.strftime("%Y-%m-%d %H:%M:%S")
    return parsed_date
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • We can't see what your `parse` method actually does. Do a `strptime` first to get a datetime obj of the strings and then call `strftime` in the expected format. – Igl3 Jun 11 '18 at 14:07
  • @rakeshdasari: `parse` is not code we have access to. You need to provide a [MCVE] if you want us to try to diagnose the problem. – ShadowRanger Jun 11 '18 at 14:11
  • @ShadowRanger parse is nothing but from dateutil.parser import parse – rakesh dasari Jun 11 '18 at 14:12
  • Could you please add a stack trace of your exceptions? – Igl3 Jun 11 '18 at 14:13
  • 1
    This code works on provided examples, do you get errors with this exact examples? – zipa Jun 11 '18 at 14:13
  • @rakeshdasari: Okay, so that's something. Can you provide the tracebacks? And the (minimal) code used to call `parse_date`? As is, we can only guess at what you're passing, the exact error messages, etc. – ShadowRanger Jun 11 '18 at 14:13

3 Answers3

0

There must be something else going wrong, you'll have to elaborate your code/exceptions.

>>> from dateutil.parser import parse
>>> date1 = "2018-05-31 14:34:42+00:00"
>>> date2 = "2018-05-21T14:49:52.833"
>>> date3 = "2018-06-01 00:00:00"
>>> print( parse(date1).strftime("%Y-%m-%d %H:%M:%S"))
2018-05-31 14:34:42
>>> print( parse(date2).strftime("%Y-%m-%d %H:%M:%S"))
2018-05-21 14:49:52
>>> print( parse(date3).strftime("%Y-%m-%d %H:%M:%S"))
2018-06-01 00:00:00
Rolf of Saxony
  • 21,661
  • 5
  • 39
  • 60
0

Where do you get an exeption, because i've tried this and it works:

date1 = "2018-05-31 14:34:42+00:00"
date2 = "2018-05-21T14:49:52.833"
date3 = "2018-06-01 00:00:00"

requestedDates = date1,date2,date3

from dateutil.parser import parse
def parse_date(request_date):
    request_date = parse(request_date)
    parsed_date = request_date.strftime("%Y-%m-%d %H:%M:%S")
    return parsed_date


for i in requestedDates:
    print(parse_date(i))

Output:
2018-05-31 14:34:42
2018-05-21 14:49:52
2018-06-01 00:00:00

The types that i'm using as dates are string, are you sure the values you're giving to the function are string? (You could check if they are by the type(date1) function)

-1

How about trying this

from datetime import datetime as dt
>>> date_str='12/20/2014 15:25:05 pm'

>>> date_obj = dt.strptime(date_str, '%m/%d/%Y %H:%M:%S %p')

>>> dt.strftime(date_obj, '%m/%d/%Y %I:%M:%S %p')
'12/20/2014 03:25:05 PM'
Nitin
  • 396
  • 7
  • 18