-1

I have found a question at this link that almost answers what I need but not quite. What I need to know, how using this method could I convert a string of the format u'Saturday, Feb 27 2016' into a Python date variable in the format 27/02/2016?

Thanks

Community
  • 1
  • 1
gdogg371
  • 3,879
  • 14
  • 63
  • 107
  • 2
    Keep reading the `datetime` documentation. There's a method called `strftime()` that goes hand in hand with the `strptime()` method described in that link. – TigerhawkT3 Aug 23 '15 at 21:45
  • 1
    What have you tried so far? Did you already read documentation on date formatting? https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior – Andrey Aug 23 '15 at 21:45

2 Answers2

4

You have to first remove the weekday name (it's not much use anyway) and parse the rest:

datetime.datetime.strptime('Saturday, Feb 27 2016'.split(', ', 1)[1], '%b %d %Y').date()

Alternatively, use dateutil:

dateutil.parser.parse('Saturday, Feb 27 2016').date()

EDIT

My mistake, you don't need to remove the Weekday (I'd missed it in the list of options):

datetime.datetime.strptime('Saturday, Feb 27 2016', '%A, %b %d %Y').date()
Ben
  • 6,687
  • 2
  • 33
  • 46
1

You don't have to remove anything, you can parse it as is and use strftime to get the format you want:

from datetime import datetime

s = u'Saturday, Feb 27 2016'

dt = datetime.strptime(s,"%A, %b %d %Y")

print(dt)    
print(dt.strftime("%d/%m/%Y"))
2016-02-27 00:00:00
27/02/2016

%A Locale’s full weekday name.

%b Locale’s abbreviated month name.

%d Day of the month as a decimal number [01,31].

%Y Year with century as a decimal number.

The full listing of directives are here

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • thanks a lot for your help again. that did exactly what I wanted. – gdogg371 Aug 23 '15 at 22:30
  • yeah pretty good thanks. i've built all the feeds i want on and off over the past year or so. just tying up some loose ends now for building a batch schedule, error checking, file size etc, logs and something to notify me if there have been any issues. then im going to start building my database. after all that is done i can hopefully do some analysis. i've also built an autoback up using the dropbox api which is good. – gdogg371 Aug 24 '15 at 00:13