flexxui / pscript

Python to JavaScript compiler
http://pscript.readthedocs.io
BSD 2-Clause "Simplified" License
256 stars 25 forks source link

Handling dates #68

Closed riziles closed 2 years ago

riziles commented 2 years ago

First of all, PScript is awesome. I love transpiling Python programs into Javascript programs that just work, like this: https://gist.github.com/riziles/87888bd508f1471a5feea1eb36d69cbb . Any suggestions as to how to handle dates easily? It seems like I'm spending a lot of time re-writing Python date functions in Javascript.

almarklein commented 2 years ago

Use the JS date system, which is pretty good: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

riziles commented 2 years ago

Thanks! I actually start using Piotr Dabkowski's package Js2Py (it has an implementation of the JS Date class) in conjunction with PScript so my code works both in Python and JS:

import js2py
import pscript

def Date(*args):
    if len(args) >= 1:
        if isinstance(args[0],str):
            return js2py.eval_js(f'new Date("{args[0]}")')
        else:
            instr = str(args[0])
            for x in args[1:]:
                instr += ',' + str(x)
            return js2py.eval_js(f'new Date({instr})')
    return js2py.eval_js(f'new Date()')

print(Date('2022-07-31T06:00:00Z').toISOString())
print(Date(2022,6,31).toISOString())
print(Date().toISOString())

print(pscript.py2js("""
print(Date('2022-07-31T06:00:00Z').toISOString())
"""))

pscript.evalpy("""
print(Date('2022-07-31T06:00:00Z').toISOString())
""")

returns:

2022-07-31T06:00:00.00Z
2022-07-31T06:00:00.00Z
2022-07-01T00:51:28.638Z
console.log((((new Date("2022-07-31T06:00:00Z")).toISOString)()));
'2022-07-31T06:00:00.000Z'