Skip to content

dateparser not able to parse things like next tuesday. #573

Closed

Description

@saroup

It parses Tuesday to the date of the Tuesday of the current week but when input is next Tuesday it returns none.

Activity

  1. tanner37 commented on Oct 21, 2019

    @tanner37

    I'm having the same issue except it's returning Tuesday of the previous week:

    >>> parse('now').strftime('%a %Y-%m-%d')
    'Mon 2019-10-21'
    >>> parse('tuesday').strftime('%a %Y-%m-%d')
    'Tue 2019-10-15'
    >>> parse('next tuesday').strftime('%a %Y-%m-%d')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'NoneType' object has no attribute 'strftime'
    
  2. GargiVyas31 commented on Mar 2, 2020

    @GargiVyas31

    Hi, I am Gargi Vyas. I am GSOC 2020 candidate and would like to work on this bug.

  3. tanner37 commented on Mar 2, 2020

    @tanner37

    That'd be awesome, Gargi. Thanks!

  4. aditya-hari commented on Mar 11, 2020

    @aditya-hari

    @Gallaecio, @noviluni
    I have looked through the code and I think I understand the gist of it at this point. What would the recommended way to tackle this? Would appreciate some suggestions to get started. A separate function in FreshnessDateDataParser maybe?

  5. Gallaecio commented on Mar 12, 2020

    @Gallaecio
    Contributor

    @aditya-hari Go ahead and propose an approach in a pull request. It’s easier to discuss over code 🙂

  6. aditya-hari commented on Mar 14, 2020

    @aditya-hari

    @Gallaecio I haven't really come up with anything concrete in code yet, can't open a pull request.

    Things like 'next tuesday' aren't identified with any locale, so there has to be some changes made in the locale info to sort that out. I am not entirely sure how to though.

    I thought about just changing the date_string to something standard like "in x days/months" but that will obviously only work for English if implemented in that way.

  7. Gallaecio commented on Mar 14, 2020

    @Gallaecio
    Contributor

    @aditya-hari I suggest you start from FreshnessDateDataParser.parse, go through what the code does keeping the target strings in mind (e.g. “Next Tuesday”), and make the required changes as you go. I see for example that ago and in are hardcoded in some parts, I guess you will need to add next there.

    You could add a test for “Next Tuesday”, extend FreshnessDateDataParser.parse as needed until it is parsed successfully, and then make sure no other tests are broken after your changes.

  8. aditya-hari commented on Mar 15, 2020

    @aditya-hari

    @Gallaecio

    Sorry it is taking me this long, I have something sort of working, I will hopefully open a PR soon. However the way I am doing this won't be able to handle the "after 15 days" situation mentioned in #635

  9. Gallaecio commented on Mar 16, 2020

    @Gallaecio
    Contributor

    Not a problem. It’s OK to just fix “Next ” for now, we can improve things later with additional, separate changes.

  10. jgtimestuff commented on Mar 20, 2020

    @jgtimestuff

    There are a lot of time-related translations available in the unicode-cldr xml or json files that could definitely be used to augment dateparser.py with things that handle all sorts of variations like 'Next Tuesday'. Of course, I'd also like to see something that cover 'Next Weekend' or 'on the weekend'... but it doesn't look like that's been defined as yet.

    Anyway, what would it take to pull in the cldr datefields for each language and incorporate them?

    https://github.com/unicode-cldr/cldr-dates-full/blob/master/main/ru/dateFields.json

  11. jgtimestuff commented on Mar 20, 2020

    @jgtimestuff

    Okay, just saw this issue from 2 years ago -- cldr_language_data | move data directory | 2 years ago
    So, is it just that the cldr_language_data needs updating to include more variations of 'next'?

    My apologies... it seems there is a script to do just this already in the code:
    #487 CLDR script update - https://github.com/scrapinghub/dateparser/compare/cldr-script-update

    Is the current dictionary up to date or is it just that the existing code isn't calling things like 'next' that already exist in the code?

  12. jgtimestuff commented on Mar 20, 2020

    @jgtimestuff

    In freshness_date_parser, I think we need to add something from calendar to get the right day of the week?

        td = relativedelta(**kwargs)
    

    relativedelta arguments for 'next' + dayofweek needs to add a day, then check the calendar for the next one?

    today = datetime.datetime.now() (happens to be Friday)
    today + relativedelta.relativedelta(weekday=calendar.FRIDAY)

    today + rld.relativedelta(weekday=calendar.FRIDAY)
    datetime.datetime(2020, 3, 20, 8, 55, 7, 615746) [today, instead of next friday]

    so, we have to add a day to today, then look for next Friday:

    today + rld.relativedelta(days=+1)
    datetime.datetime(2020, 3, 21, 8, 55, 7, 615746)
    today = today + rld.relativedelta(days=+1)
    today + rld.relativedelta(weekday=calendar.TUESDAY)
    datetime.datetime(2020, 3, 24, 8, 55, 7, 615746)
    today + rld.relativedelta(weekday=calendar.FRIDAY)
    datetime.datetime(2020, 3, 27, 8, 55, 7, 615746) [ Next Friday ]

    today = today + rld.relativedelta(days=+1)
    today + rld.relativedelta(weekday=calendar.TUESDAY)
    datetime.datetime(2020, 3, 24, 8, 55, 7, 615746) [ Next Tuesday ]

  13. jgtimestuff commented on Mar 23, 2020

    @jgtimestuff

    Thanks, after reading through that link, it seems that is about extending linguistic terms beyond what is provided by the CLDR json files. It looks to me like the json files from CLDR were last imported to dateparser in 2018 and they seem to have a lot less options for relative terms (in English as well as all languages) than what is currently available. This might aid in fixing the 'next weekday' issue...

    Although, supplementing that data with 'weekend' would definitely fall under extending the terms as the files don't seem to cover terms like weekend or perhaps even 'fortnight' used by Aussie's etc...

  14. jgtimestuff commented on Mar 23, 2020

    @jgtimestuff

    Ahh wait, now I see that this script looks at the CLDR but only chooses a subset of the available relative terms to transition to dateparser.

    https://github.com/scrapinghub/dateparser/blob/master/scripts/get_cldr_data.py

  15. Gallaecio commented on Apr 9, 2020

    @Gallaecio
    Contributor

    So we might want to extend that subset as needed by changing the download script, and re-running.

  16. thinow commented on Sep 21, 2021

    @thinow

    Hi everyone,
    Thanks for looking at this issue. There is no updates since more than one year. Any work around we could use?

  17. anarcat commented on Mar 24, 2022

    @anarcat
    Contributor

    my workaround is to load both dateparser and parsedatetime and use the latter when the former fails. :)

  18. tanner37 commented on Apr 4, 2022

    @tanner37

    This is my work around:

    days_long = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
    for day in days_long:                                                                    
        print('trying to find:', day)                                                        
        if day in time:                                                                      
            print('found', day)                                                              
            delta = 1                                                                        
            while day not in (datetime.now() + timedelta(days=delta)).strftime('%A').lower():
                delta += 1                                                                   
                print('delta:', delta)                                                       
                if delta > 14: raise # just to make sure                                     
            if re.findall(r'\d|noon|midnight', time):                                        
                date = (datetime.now() + timedelta(days=delta)).strftime('%Y-%m-%d')         
            else:                                                                            
                date = daystr((datetime.now() + timedelta(days=delta)))                      
            print('date:', date)                                                             
            time = time.replace(day, date).replace('next', '')                               
            print('time:', time)                                                             
            break # only first match                                                         
        else:                                                                                
            print('not found')                                                               
    

    It's janky, but it works.

  19. gaoxiaoliang commented on Jul 27, 2026

    @gaoxiaoliang

    I'd like to pick this up (this also covers the duplicates #1177 "last monday" and #635 "Last Sunday"). Since PR #638 stalled on design rather than code, I want to agree on the expected behavior before opening a PR.

    Root cause (why next tuesday returns None today)

    last/next/this <weekday> is not handled by the relative-time (freshness) parser — that path only understands <number> <unit>, and last week works only because it is statically rewritten to 1 week ago. A weekday has no fixed magnitude, so the string falls through to the token parser, where next/last/this are unrecognized tokens and raise ValueError.

    Meanwhile the token parser already resolves a bare weekday (Friday) and already honors PREFER_DATES_FROM. So the fix is to capture the modifier word and route it into the existing weekday-resolution logic — no new calendar math is required.

    Proposed semantics

    last/next share the same week-boundary ambiguity (e.g. on a Wednesday, "last Monday" can mean this week's Monday or last week's Monday). I propose one symmetric setting to control it, defaulting to everyday conversational usage (the adjacent calendar week):

    phrase default (adjacent week) opt-in (nearest occurrence)
    next friday Friday of next week the coming Friday
    last friday Friday of last week the most recent past Friday
    this friday Friday of the current week (same)

    this <weekday> is unambiguous — the weekday within the current calendar week.

    Scope (kept narrow, per CONTRIBUTING)

    • English first. The last/next/this lexicon already exists in the CLDR data, so extending to other locales becomes a follow-up data task rather than being attempted in one PR (that is what sank Adding after and next keywords with basic functionality. #638).
    • Works in both parse() and search_dates(), and combines with a time part (next friday at 5pm, 12am last monday).

    Questions for maintainers before I open the PR

    1. Is "adjacent calendar week" an acceptable default, with an opt-in for the nearest-occurrence interpretation?
    2. Any preference on the new setting's name? (e.g. something in the PREFER_* family.)
    3. Is an English-first PR acceptable, with a documented path to add the modifier words for other locales afterwards?
  20. AdrianAtZyte commented on Jul 28, 2026

    @AdrianAtZyte
    Member
    Opus feedback
    Fetched it (comment by gaoxiaoliang, 2026-07-27) and checked each claim against master. Here's my assessment.
    
    Their diagnosis is accurate, with one correction
    
    Verified on master (base Tue 2026-07-28):
    
    'friday'         current_period  Fri 2026-07-24     'next friday'   None
    'friday'         future          Fri 2026-07-31     'last monday'   None
                                                        'this friday'   None
    
    - Freshness parser only matches <number> <unit> (PATTERN in freshness_date_parser.py:13) — correct.
    - last week works only via the static relative-type rewrite to 1 week ago — correct; locale.translate("last week") → '1 week ago', while translate("next friday") → 'next  friday' (modifier untouched, then the token parser bails).
    - Bare weekday is already resolved in parser.py:479 _correct_for_time_frame, already honoring PREFER_DATES_FROM — correct, and it's the right place to put this.
    
    The correction: the weekday lexicon is not already in dateparser's CLDR data. get_cldr_data.py:75-81 only pulls year/month/week/day/hour/minute/second keys; the per-weekday keys (mon, mon-short, mon-narrow → relative-type--1/0/1 = "last Monday"/"this Monday"/"next Monday") exist upstream in dateFields.json but are filtered out on import. That's good news for their Q3 — see below.
    
    Q1: I'd push back on "adjacent calendar week" as the default
    
    1. It isn't well-defined without a week start. "Friday of next week" depends on when the week begins, which varies by locale (en-US Sunday, en-GB Monday). We do have DEFAULT_START_OF_WEEK (dateparser_data/settings.py:32, default monday, added for RETURN_TIME_SPAN), so no new setting is needed for it — but that means parse("next friday") would silently depend on a setting whose default disagrees with the convention for a large share of English users. Nearest-occurrence needs no week concept at all.
    2. Their "unambiguous" case isn't. Base Tue 2026-07-28: bare sunday → 2026-07-26. this sunday under current-calendar-week gives 2026-08-02 with Monday-start, 2026-07-26 with Sunday-start. Two answers for the phrase they call unambiguous, and one of them disagrees with bare sunday.
    3. Current-week resolves forward-looking phrases into the past. "this Monday" said on a Friday means the coming Monday to almost every speaker; current-calendar-week puts it 4 days back. That will get filed as a bug.
    4. Consistency with what already works. friday + PREFER_DATES_FROM='future' already means "the coming Friday". Having next friday mean something different from friday-plus-future, when next is the only added token, is surprising.
    
    My preference: next <weekday> = first occurrence strictly after the base; last <weekday> = most recent strictly before; this <weekday> = the coming occurrence, with today mapping to today. That is "pin PREFER_DATES_FROM to future/past for this string, with a strict inequality" — a small change inside the existing _correct_for_time_frame branch, no calendar math, no week start. Note the strictness matters and it converges with their reading in the case people are most confident about: on a Friday, next friday → +7 days either way.
    
    Q2: I'd rather not add a setting at all
    
    English already has unambiguous phrasings for the other reading — "Friday next week", "a week from Friday". Those can be added later as data without changing any default, which is the cheap way out of this deadlock: ship the unambiguous cases, leave the disputed one to explicit phrasing. A setting added now locks in semantics we can't revise; a setting added later breaks nobody. And if one does turn out to be needed, it shouldn't join the PREFER_* family — every existing PREFER_* expresses a past/future direction, and this isn't that.
    
    Q3: skip English-first — the script route is nearly free
    
    Since the weekday relative strings are in CLDR and only filtered out on import, extending the key list in get_cldr_data.py + write_complete_data.py gets ~all locales mechanically instead of English plus a follow-up that historically never lands. One real design task hides there: CLDR gives whole phrases ("martes próximo", "am nächsten Dienstag"), and relative-type can only map to N unit ago strings, which can't express a weekday. So a new canonical target is needed — CLDR phrase → canonical next monday → parser logic. That's the piece worth agreeing on before code, more than the default semantics.
    
    Things to flag for the PR
    
    - Don't regress next month/week/year/decade — they're relative-type entries; substitution ordering matters.
    - search_dates already regexes (?:next|coming|following)\s+week in dateparser/utils/time_spans.py:detect_time_span; make sure the two don't fight.
    - _correct_for_time_frame mutates self._token_month (parser.py:511) to protect against _correct_for_month — easy trap.
    - Keep period='day'; friday at 5pm already works, so next friday at 5pm should fall out, but test it.
    - Test matrix over 7 weekdays × 7 base weekdays × {next,last,this} with RELATIVE_BASE, plus explicit coverage that next/last override PREFER_DATES_FROM.
    - "coming friday", "previous friday", "this past friday" won't come from CLDR — supplementary data, separate PR.
    
  21. gaoxiaoliang commented on Jul 28, 2026

    @gaoxiaoliang

    You're right, and I apologize. I opened the PR without checking your reply, so it went out reversing the very positions I'd asked about, without engaging your pushback. That's on me.

    Having gone through your reasoning, I agree on all three:

    • I had the semantics of "last/next " wrong. Modeling them as "which calendar week" is what created the week-start dependency and the backwards "this Monday" result. Your strict nearest-occurrence rule (next = first occurrence strictly after the base, last = most recent strictly before, this = the coming one with today mapping to today) is well-defined, needs no week-start, and lines up with bare-weekday + PREFER_DATES_FROM. I'll switch to that.
    • I'll drop the PREFER_WEEK setting. The other reading is better served by explicit phrasing ("Friday next week") added as data later, and a setting locks us in for nothing.
    • I'll go the CLDR route instead of English-first, extending the key list so the weekday relative strings that are currently filtered out on import come through for all locales. I'll work out the canonical-target piece (CLDR phrase to a canonical "next monday" the parser understands) since relative-type can't express a weekday directly.

    I'll also fix the concrete regressions you found in the PR (the "the last three commits" false positive, the modifier being swallowed into the match span, and the wrong README example), and expand the tests to the 7x7x3 matrix plus coverage that next/last override PREFER_DATES_FROM.

    Thanks for the thorough review. I'll update the PR.

  22. added a commit that references this issue on Oct 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions