playwright-python icon indicating copy to clipboard operation
playwright-python copied to clipboard

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

Open DetachHead opened this issue 1 year ago • 0 comments

🚀 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:

https://github.com/microsoft/playwright-python/blob/445f80a0d9864898d8f1cd0518c147b24850b873/playwright/_impl/_js_handle.py#L243-L247

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.

DetachHead avatar Dec 04 '24 03:12 DetachHead