Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix skipping day when parsing times if UTC and TIMEZONE day are different #1183

Merged
merged 1 commit into from Dec 18, 2023

Conversation

MxMarx
Copy link
Contributor

@MxMarx MxMarx commented Sep 14, 2023

This should fix #1169

If only a time is provided such as "8pm", the previous logic determines if the time is in the "future" or "past" by comparing the base time of day and the parsed time.
This works if the timezone is UTC, but to make this respect the TIMEZONE setting, #1002 subtracts the timezone's offset from the parsed time. If this causes the day to roll over, then comparing times will incorrectly report the parsed date as being in the past. For example. datetime(2023, 2, 3, 4).time() == datetime.time(4, 0) is reported as earlier tham datetime(2023, 2, 2, 18).time() == datetime.time(18, 0), and erroneously adding day. To correct this, we could compare dates rather than times.

from datetime import datetime
import dateparser
import pytz

now = datetime(2023, 2, 2, 10).astimezone(pytz.timezone("America/Los_Angeles"))
print(now)      # 2023-02-02 10:00:00-08:00
now_utc = now.astimezone(pytz.timezone("UTC")).replace(tzinfo=None)
print(now_utc)  # 2023-02-02 18:00:00

settings = {
    'PREFER_DATES_FROM': 'future',
    'RETURN_AS_TIMEZONE_AWARE': True,
    'RELATIVE_BASE': now_utc,
    'TIMEZONE': 'America/Los_Angeles',
    "TO_TIMEZONE": "etc/utc",
}
time = dateparser.parse('2pm', settings=settings)
print(time) # 2023-02-02 22:00:00+00:00 - correct

time = dateparser.parse('8pm', settings=settings)
print(time) # 2023-02-04 04:00:00+00:00 - incorrect

# datetime(2023, 2, 3, 4).time() = datetime.time(4, 0)
# datetime(2023, 2, 2, 18).time() = datetime.time(18, 0)
# datetime.time(4, 0) < datetime.time(18, 0) which causes date to be added even though the date is in the future

Copy link
Contributor

@Baviaan Baviaan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for making these changes, looks good!

@Gallaecio
Copy link
Member

Closing and reopening to trigger CI (hopefully).

@Gallaecio Gallaecio closed this Dec 18, 2023
@Gallaecio Gallaecio reopened this Dec 18, 2023
@Gallaecio Gallaecio merged commit 5bddb9f into scrapinghub:master Dec 18, 2023
11 checks passed
@Gallaecio
Copy link
Member

Perfect, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Returned datetime skips a day
3 participants