2

Is there a quick way to convert a string to a datetime object in Python WITHOUT having to specify the format?

I know I can do:

datetime.strptime('Sun 10 May 2015 13:54:36 -0700', '%a %d %b %Y %H:%M:%S %z')

But since this is the default format, is there someway to get it to autoparse? Seems like I should be able to just create a new object from this without having to specify the format since it is the default system format.

Zack
  • 2,377
  • 4
  • 25
  • 51
  • @mypetlion my question is that since the string is in the default format is there a quick way. That question is different format. – Zack Jul 31 '18 at 21:30
  • `datetime.datetime.strptime` is the function used by the top answer in that question and it allows you to specify a format. See [here](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior) for a guide on how to specify a format. – mypetlion Jul 31 '18 at 21:33
  • @mypetlion you are missing the entire point of the question... I'm well aware of strptime. Edited the question so hopefully it is more clear. – Zack Jul 31 '18 at 22:09

1 Answers1

1

use parser.parse method from dateutil module. You can install it by doing pip install python-dateutil

>>> from dateutil import parser
>>> parser.parse('Sun 10 May 2015 13:54:36 -0700')
datetime.datetime(2015, 5, 10, 13, 54, 36, tzinfo=tzoffset(None, -25200))
Sunitha
  • 11,777
  • 2
  • 20
  • 23