0

having trouble converting this string into a datetime this is what I tried so far in code:

import datetime

mystring = '2016/5/7/  4:25:00 PM'
dateobj = datetime.datetime.strptime(mystring, "%Y-%B-%dT%H:%M:%S-%H:%M")
print (dateobj)

it throws me errors and I search in the library and still can't figure it out what I have wrong in my format. Please any help I'll gratly apreciate it

herrington
  • 65
  • 9
  • yea I am sorry I'll doble check before posting they are non related they were just example and its edited :-) – herrington Jun 01 '16 at 11:47

4 Answers4

1

You can do it as:

import datetime    
mystring = '2016/5/7 4:25:00 PM'


dateobj = datetime.datetime.strptime(mystring, "%Y/%m/%d %I:%M:%S %p")

dateobj
Out[1]: datetime.datetime(2016, 5, 7, 16, 25)

dateobj1 = datetime.datetime.strptime(mystring, "%Y/%m/%d %I:%M:%S %p").strftime("%Y-%m-%d %I:%M:%S")

dateobj1
Out[2]: '2016-05-07 04:25:00'
shivsn
  • 7,680
  • 1
  • 26
  • 33
0

The issue you are having is that in order to convert a date object you first have to create a date object. This means that your formatting will have to match the current string format '2016/5/7 4:25:00 PM' = "%Y/%m/%d %H:%M:%S %p". So we can now create a date obj and then format it using strftime with your new format "%Y-%B-%dT%H:%M:%S-%H:%M".

import datetime

mystring = '2016/5/7 4:25:00 PM'
dateobj = datetime.datetime.strptime(mystring, "%Y/%m/%d %H:%M:%S %p")
dateobj = datetime.datetime.strftime(dateobj, "%Y-%B-%dT%H:%M:%S-%H:%M")
print (dateobj)

the output recieved is a little funky, but it matches your format perfectly. Visit the datetime library to view the format codes and read up on strptime vs strftime. Good luck.

Output: 2016-May-07T04:25:00-04:25

TheLazyScripter
  • 2,541
  • 1
  • 10
  • 19
0

I'm not sure where your format string came from, but it's wrong. It doesn't match your string format at all.

Take a look at the available options in the documentation.

You want this:

dateobj = datetime.datetime.strptime(mystring, "%Y/%m/%d/ %I:%M:%S %p")

This will get you a date object. You can then do this to reformat it how you want:

dateobj.strftime("%Y-%m-%d %I:%M:%S")

A couple things that were wrong with yours:

  • You used %H twice. This resulted in an error saying it'd be redefined.
  • %B is full month name (ie. January). You have a numeral.
  • The -s are incorrect since you have /s.
  • The T is not in your string at all.
Andy
  • 49,085
  • 60
  • 166
  • 233
0

Easily with dateutil.parser.parse

>>> from dateutil.parser import parse
>>> d = parse('2016/5/7/  4:25:00 PM')
>>> d.strftime("%Y-%B-%dT%H:%M:%S-%H:%M")
'2016-May-07T16:25:00-16:25'
>>> d.strftime("%Y-%m-%d %I:%M:%S")
'2016-05-07 04:25:00'
pacholik
  • 8,607
  • 9
  • 43
  • 55