py-datetime
v0.9.1
Published
Datetime handling the python way (or as close as possible)
Downloads
36
Maintainers
Readme
Python-style datetime handling lib for ES6
This tiny lib emulates most of the main functions of Python's datetime lib to simplify datetime handling in JavaScript that is notoriously cumbersome in this regard. It tries to stay as close to the python API as possible - ideal if you are working with both Python and JS projects. Hope you'll find it useful! Live console here: https://npm.runkit.com/py-datetime
Install
npm install py-datetime
Demo
import {default as dt} from "py-datetime"; // const dt = require("py-datetime"); for node imports
let now = dt.datetime.now()
let today = dt.datetime.combine(now, dt.time())
console.log("Now:", now.strftime("%Y-%m-%d %H:%M:%S"));
console.log("Today:", today.strftime("%Y-%m-%d"));
console.log("Minutes since midnight:", dt.timedelta(now - today).totalSeconds() / 60);
A few gotchas
dt.timedelta(days, [seconds, [milliseconds..)
constructor can't really guess whether you are passing in a day or a result from date math (as dt - dt in javascript will return an int), so i've arbitrarily put in a condition where if it's under 900 we treat it as days, but otherwise it's millis (1000 millis = 1 sec). For most cases this should work just fine, but where disambiguation is required, you can be be explicit about it:dt.timedelta({days: ..})
and `dt.timedelta({millisesconds: ..}), respectively.- use
.str()
to get string representation of the object. JavaScript'stoString()
will return Unix epoch.
List of supported functions
Note: all objects evaluate to milliseconds, meaning dt.datetime.now() + 0
will give you time in Unix epoch. you can also call
<object>.toString
directly.
dt.datetime
dt.datetime(year, month, day, hour, minute, second, millisecond)
- gets you a brand new datetimedt.datetime(jsDate)
- you can also pass in a JavaScript Date objectdt.datetime(unixEpoch)
- this will also workdt.datetime(datetime)
- this will clone an existing datetime object)dt.datetime.strptime(dateString, format, utc)
- parse given date string into a new datetime. Format uses posix parsing see d3-time-format for details. The third param is an optional boolean. When set to true, dateString will be assumed to be in UTC.dt.datetime.now()
- return current timedt.datetime.utcnow()
- return current time in UTCdt.datetime.combine(date, time)
- combines passed indt.date
ordt.datetime
with the passed indt.time
to create a new datetimedatetime.replace(year, month, day, hour, minute, second, millisecond)
returns a new datetime with items replaced as requesteddatetime.jsDate
property returns JavaScript Date object representing the datetimedatetime.str()
returns analog of python'sstr(datetime)
which is%Y-%m-%d %H:%M:%S.%f
dt.date
dt.date(year, month, day)
- creates a, well, timeless object, all three params are mandatorydate.jsDate
property returns JavaScript Date object representing the datetimedatetime.str()
returns analog of python'sstr(date)
, which is%Y-%m-%d
dt.time
dt.time(hour, minute, second, millisecond)
- return a new time objectdt.time(time)
- clone an existing dt.time objecttime.str()
returns analog of python'sstr(time)
, which is%H:%M:%S.%f
dt.timedelta
dt.timedelta(days, seconds, milliseconds, minutes, hours, weeks)
- return a new time object. the param order is not random and matches python.dt.timedelta(millis)
- this will work if millis is > 900. will initiate the timedelta object from milliseconds. this is so you can dodt.timedelta(dateA - dateB)
. See gotchas higher up for the 900 thing.timedelta.totalSeconds()
- returns total seconds between the two times.timedelta.str()
returns analog of python'sstr(time)
, which is%H:%M:%S.%f
Dealing with UTC
py-datetime is timezone naive, but dates and times around daylight savings can get bit iffy. There are two functions that help mitigate that
dt.datetime.utc()
- pass in JS datetime in UTC timezone or unix epoch. the datetime object will be marked as operating in UTCdt.datetime.strptime
- if you pass in the date string in UTC, make sure to specify the third optional param totrue
. from there on out this date object will be marked as operating in UTC.
Be mindful around datemath, e.g. z = dt.datetime(dt.datetime.utc(someDate) + dt.timedelta(1))
will lose the UTC information, so
you should do z = dt.datetime.utc(dt.datetime.utc(someDate) + dt.timedelta(1))
.
The API is bit sucky at the moment, so if you have any good ideas - pull requests welcome!