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

[Feature]: datetime values parsed by the evaluate method should be converted to the current context's timezone #2681

Open
DetachHead opened this issue Dec 4, 2024 · 0 comments

Comments

@DetachHead
Copy link

DetachHead commented Dec 4, 2024

🚀 Feature Request

when parsing a javascript Date object to a python datetime object, playwright correctly parses the string with the UTC timezone, since that's how js dates are are stored internally:

# Node.js Date objects are always in UTC.
return datetime.datetime.strptime(
value["d"], "%Y-%m-%dT%H:%M:%S.%fZ"
).replace(tzinfo=datetime.timezone.utc)

however they do not get converted back to the browser context's timezone, which can be a source of bugs when working with datetimes in python, for example:

from datetime import datetime

from playwright.sync_api import sync_playwright

with sync_playwright() as pw:
    page = (
        pw.chromium.launch(headless=False)
        .new_context(timezone_id="Australia/Sydney")
        .new_page()
    )
    # imagine we're getting a date from something on the page that we then need to then input into a date field,
    # in this case we get January 1 2020
    date: datetime = page.evaluate("() => new Date(2020,0,1)")
    # we assume the timezone is correct, because the browser is configured to use that timezone, but once we try
    # to use the value, it's wrong (December 31 2019)
    page.locator("input").fill(date.strftime("%d/%m/%Y"))

i think the solution is for playwright to convert the datetime object to the browser context's timezone once it's already been parsed using UTC, so something like this:

 if "d" in value:
     # Node.js Date objects are always in UTC.
     return datetime.datetime.strptime(
         value["d"], "%Y-%m-%dT%H:%M:%S.%fZ"
-    ).replace(tzinfo=datetime.timezone.utc)
+    ).replace(tzinfo=datetime.timezone.utc).astimezone(context.timezone)

Example

No response

Motivation

this will make it less likely for users to accidentally introduce timezone-related bugs in their code.

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

No branches or pull requests

1 participant