0

I need a Python Datetime in a yyyy-mm-dd format, but don't really know the best way to take something like this "Tuesday July 7, 2015" and turn it into that.

I'm assuming I would have to extract out the text for the day of the week, which is a pain because it can be any day of the week, once, i Have the rest of the format I could probably use Python built in Datetime to turn it from a string to a datetime object, but my question is, is this the best way?

PythonIsGreat
  • 7,529
  • 7
  • 21
  • 26

3 Answers3

3

Here's a overview of the format codes: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

The full set of format codes supported varies across platforms, because Python calls the platform C library’s strftime() function, and platform variations are common. To see the full set of format codes supported on your platform, consult the strftime(3) documentation.

But your example should be parseable with %A %B %d, %Y:

>>> import datetime
>>> datetime.datetime.strptime("Tuesday July 7, 2015", "%A %B %d, %Y")
datetime.datetime(2015, 7, 7, 0, 0)
miku
  • 181,842
  • 47
  • 306
  • 310
1

You can have both the %A and %d format specifiers in the same format string with strptime:

>>> datetime.datetime.strptime("Tuesday July 7, 2015", "%A %B %d, %Y").date()
datetime.date(2015, 7, 7)
Raniz
  • 10,882
  • 1
  • 32
  • 64
1
from datetime import datetime
datetime.strptime("Tuesday July 7, 2015", "%A %B %d, %Y").strftime("%Y-%m-%d")

The output

http://testedanswers.com/questions/-JsXzg2WOR2IXFRqwT1Q

JuanPablo
  • 23,792
  • 39
  • 118
  • 164