简体   繁体   中英

Convert Spanish date in string format?

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, eg

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM