How would I convert a date in string format to compare it with the current time?
I tried this:
import time, datetime
if time.strptime(date.find(text=True), "%a, %d/%m/%Y").now() > datetime.now():
But I get this error:
ValueError: time data u'Dom, 07/02/2016' does not match format '%a, %d/%m/%Y'
Need advice on how to do this.
You need to setup the proper locale before handling language/region specific data.
Try again with
import locale
locale.setlocale(locale.LC_TIME, '')
time.strptime(date_string, "%a, %d/%m/%Y")
The ''
tells the library to pickup the current locale of your system (if one is set).
If you need to parse the date in a different locale, the situation is a little bit more complex. See How do I strftime a date object in a different locale? for the gritty details.
It is possible to explicitly set a specific locale, e.g.
locale.setlocale(locale.LC_TIME, 'es_ES.UTF-8')
time.strptime('Dom, 01/02/1903', '%a, %d/%m/%Y')
=> time.struct_time(tm_year=1903, tm_mon=2, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=32, tm_isdst=-1)
but remember, that this setting is global. strptime()
does not accept a parameter to specify a particular locale to parse with, it always picks up the global locale.
If the date is user-supplied, I have used dateparser
package as a welcome alternative. Especially so, since its parse()
function accepts an explicit languages
parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With