4

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.

jfs
  • 399,953
  • 195
  • 994
  • 1,670
user2520969
  • 1,389
  • 6
  • 20
  • 30
  • 2
    Did you set the correct locale? What does `locale.getlocale(locale.LC_TIME)` return? – dhke Feb 05 '16 at 14:50
  • name 'locale' is not defined ... – user2520969 Feb 05 '16 at 14:51
  • 2
    It works if "Dom" is replaced by "Sun" so I also assume it is a locale issue. – Uraza Feb 05 '16 at 14:52
  • 1
    `import locale` should solve that. [`locale`](https://docs.python.org/2/library/locale.html) is a standard module that deals with --well-- the locale, i.e. encodings, currency and date/time formats. You are probably parsing your date in `'C'` locale, which has no notion of Spanish(?) `'Dom'`. You need to setup the proper locale when parsing localized date/time. – dhke Feb 05 '16 at 14:52
  • related: [Python strptime finnish](http://stackoverflow.com/q/33375709/4279) – jfs Feb 09 '16 at 04:44

1 Answers1

18

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.

dhke
  • 15,008
  • 2
  • 39
  • 56