Pendulum – Python datetimes made easy
github.com
github.com
It is heavily inspired by [Carbon](http://carbon.nesbot.com) for PHP.
Basically, the Pendulum class is a replacement for the native datetime one with some useful and intuitive methods, the Interval class is intended to be a better time delta class and, finally, the Period class is a datetime-aware timedelta.
Timezones are also easier to deal with: Pendulum will automatically normalize your datetime to handle DST transitions for you.
import pendulum
pendulum.create(2013, 3, 31, 2, 30, 0, 0, 'Europe/Paris’)
# 2:30 for the 31th of March 2013 does not exist
# so pendulum will return the actual time which is 3:30+02:00
'2013-03-31T03:30:00+02:00’
dt = pendulum.create(2013, 3, 31, 1, 59, 59, 999999, 'Europe/Paris’)
'2013-03-31T01:59:59.999999+01:00’
dt = dt.add(microseconds=1)
'2013-03-31T03:00:00+02:00’
dt.subtract(microseconds=1)
'2013-03-31T01:59:59.999998+01:00’
To those wondering: yes I know [Arrow](http://crsmithdev.com/arrow/) exists but its flaws and strange API (you can throw almost anything at get() and it will do its best to determine what you wanted, for instance) motivated me to start this project. You can check why I think Arrow is flawed here: https://pendulum.eustace.io/faq/#why-not-arrowLink to the official documentation: https://pendulum.eustace.io/docs/
Link to the github project: https://github.com/sdispater/pendulum
At least that was my impression from trying to find a combination of libraries I like and reading various bug trackers in the process. In the end I pick and choose the pieces that do what I like for each part of the process, luckily the datatypes are mostly compatible or easily adapted.
I'm doing a `pip install https://dev.mysql.com/get/Downloads/Connector-Python/mysql-c... on older centos boxes. Because I found `pip install mysql-connector-python` seems to fail on older boxes.
I also wonder if I should not start to look at SQLAlchemy. Not so much the ORM. But rather the simple DBAPI[0] interface.
I'm already using Postgres FDW to integrate PostGIS into our mysql dbs. So I am going to drag a Postgres python lib around in the near future, any recommendations.
PS: I Believe I just convinced myself, to go invest some time into learning SQLAlchemy.
What is important here, I think, is that any time arithmetic is not affected by this normalization, so if you add an hour the difference will be an hour, so you don't really have to think about it.
So somebody clearly made a mistake (either the user or the programmer not checking the input) which you can't automagically fix. Well, at least, it's a terrible idea.
I understand the intent of helping them, but you make more harm this way.
It's also against the ZEN of Python.
Obviously automatic normalisation is the correct thing to do when doing arithmetic that crosses DST-rollover boundaries (this is what the Python stdlib gets wrong), but I don't think it should be done (by default) upon creation with a location-based TZ specification:
pendulum.create(2016, 10, 30, 2, 30, 00, 0, 'Europe/Paris') is ambiguous, and pendulum.create(2016, 3, 27, 2, 30, 00, 0, 'Europe/Paris') is non-existent. pytz raises AmbiguousTimeError or NonExistentTimeError respectively in cases where you try to construct local times like that and specifiy is_dst=None: http://pytz.sourceforge.net/#problems-with-localtime
With pendulum I don't see a possibility to enforce a "strict mode" that turns of those automatic assumptions.
I think the best thing to do here is keep the current behavior (post-DST) but with an option to choose what you want exactly (post-DST, pre-DST)
> Unfortunately, during DST transitions, some datetimes don’t exist or are ambiguous. In such situations, pytz raises an exception. Other tzinfo implementations, such as the local time zone used as a fallback when pytz isn’t installed, may raise an exception or return inaccurate results. That’s why you should always create aware datetime objects when time zone support is enabled.
https://docs.djangoproject.com/en/1.10/topics/i18n/timezones...
What if you were to begin with a time at 3:30 and then subtract an hour. Would your library properly return 1:30? What if a user had a naive time at 3:30, subtracted an hour, and then converted to an aware time using your library? For what it's worth, I think moving to 3:30 is the correct behaviour in the vast amount of cases. Requiring a user to provide a direction to move and throwing an exception if they don't is dangerous. How often are users going to see this exception, if at all? Just wondering how much you've considered cases, if they exist, that would be better off moving to 1:30.
I'll add one more thing. As soon as I started browsing the page I thought "why would I use this over arrow?". Great to see you addressed that by default. I didn't know about some of arrows shortcomings/bugs, so they were really useful.
Handling dates, times, and timezones in particular is a tricky problem, as evident by the large number of libraries in each language trying to get it right. If you haven't already, I'd really recommend reading the blog posts of Jon Skeet regarding Noda Time http://blog.nodatime.org/ and https://codeblog.jonskeet.uk/category/nodatime/ even if it turns up some corner cases you haven't considered, or validates ones you have.
Thanks!
https://www.python.org/dev/peps/pep-0495/
It adds an extra attribute 'fold' that can be '0' (the default) for normal times and '1' for the later version with that same local time representation in the case of the clock going backwards.
There have been steady discussions of this issue for almost four years now. I dropped out years ago, but the arguments go on.
Where exactly in email to do they appear? In the header, it's been my experience they all conform to the RFC 2822 spec, and could be parsed with the standard library function email.utils.parsedate_tz[1].
[1] https://docs.python.org/2/library/email.util.html#email.util...
[1] http://infiniteundo.com/post/25326999628/falsehoods-programm... [2] http://infiniteundo.com/post/25509354022/more-falsehoods-pro...
In [34]: pd.Timestamp('2016-08') == pd.Timestamp('2016.08') == pd.Timestamp('2016/08') == pd.Timestamp('08/2016')
Out[34]: True
In [38]: pd.Timestamp('2016') == pd.Timestamp(datetime.datetime(2016,1,1))
Out[38]: True
In [49]: pd.Timestamp('2016') + pd.offsets.MonthOffset(months=7) == pd.Timestamp('2016-08')
Out[49]: True
In [52]: pd.Timestamp.now()
Out[52]: Timestamp('2016-08-17 08:01:07.576323')
In [53]: pd.Timestamp.now() + pd.offsets.MonthBegin(normalize=True)
Out[53]: Timestamp('2016-09-01 00:00:00')
see http://pandas.pydata.org/pandas-docs/stable/timeseries.html for more examplesAlso I really hate when someone fragment the energy and their time making a new, inferior library instead of fixing and patching the existings for basic things like this. This way we will have a bunch of incomplete, inferior libraries which all have quirks instead of only one really good one which could everybody use...
http://delorean.readthedocs.io
http://github.hubspot.com/sanetime/
https://github.com/zachwill/moment
https://docs.djangoproject.com/en/1.10/topics/i18n/timezones...
The most similar to this are Arrow and Delorean, maybe Django timezone if you use Django.
Second, I think it's great that people are making alternatives - it promotes a healthier ecosystem where people can share good ideas as well.
> instead of fixing and patching the existings Finally, by your logic, the popular requests library shouldn't have existed and Kenneth would have been patching the more conventional urllib library
This library did not born because of fun, but because of solving a (non-existing) problem from frustration. I would have not said one word if he was doing this for fun or just learning or something like that.
Again, I'm using the example of requests: was Kennethwrong to implement something new when there was already a standard lib?
In some cases it guesses what you meant:
>>> pendulum.create(2013, 3, 31, 2, 30, 0, 0, 'Europe/Paris')
'2013-03-31T03:30:00+02:00' # 2:30 does not exist (Skipped time)
In other cases, it raises exceptions: pendulum.parse('2016-06-31')
# ValueError: day is out of range for monthOn the otherhand if you've e.g. Ruby/Rails datetime handling than you get used to reasonable things working ( such as Time.now + 1.day ) that Arrow doesn't handle well. As a matter of fact Arrow got rid of DT deltas and seemingly made the situation worse.
I've only looked at the examples in the docs; but to be serious, Python should just scrap their DT/time/calendar libs and copy Ruby verbatim. This NIH thing needs to stop..
I don't see anything unreasonable about Pendulum's interface. Let's let Python be Python and Ruby be Ruby.
[0]: http://ruby-doc.org/core-1.9.3/Integer.html#method-i-times
Sorry for the rant, but I've spent many years as the only California developer for a time based in the UK, suffering the tyranny of developers who spend half their year blissfully living in UTC and unknowingly foisting off their dirty time zone bugs on me.
Related: http://stackoverflow.com/questions/441147/how-can-i-subtract...
now_in_paris = pm.now('Europe/Paris')
tomorrow_in_paris = now_in_paris + pm.day
next_week_in_paris = now_in_paris + 7*pm.day
https://github.com/sdispater/pendulum/issues/17 >>> from datetime import datetime, timedelta
>>> datetime.now() - (datetime.now() + timedelta(days=1))
datetime.timedelta(-2, 86399, 999969)Try:
>>> from datetime import datetime, timedelta
>>> now = datetime.now()
>>> now - (now + timedelta(days=1))
datetime.timedelta(-1)That a timedelta can be represented in multiple ways is alone quite surprising but some of the representations that happen can be very confusing. I think the example I gave which represents "-1 day and a few microseconds" as "-2 days + 86399 milliseconds + 999969 microseconds" is very surprising and it commonly happens in practice.
For comparison, here's what postgres does:
postgres=> select now() - (now() + '12 milliseconds'::interval + '1 day'::interval);
?column?
-----------------------
-1 days -00:00:00.012
(1 row) d1 = datetime(2012, 1, 1, 1, 2, 3, tzinfo=pytz.UTC)
d2 = datetime(2011, 12, 31, 22, 2, 3, tzinfo=pytz.UTC)
delta = d2 - d1
delta.days
-1
delta.seconds
75600
d1 = Pendulum(2012, 1, 1, 1, 2, 3)
d2 = Pendulum(2011, 12, 31, 22, 2, 3)
delta = d2 - d1
delta.days
0
delta.hours
-3The README for Pendulum seems to show me one feature Delorean doesn't explicitly have -- `is_weekend()` -- otherwise these libraries are conceptually very similar.
I do agree that this (and Delorean) is a usability improvement over `datetime` and perhaps even Arrow (though I'm not tremendously familiar with Arrow).
How can I do this with datetime+dateutil+pytz?
http://babel.pocoo.org/en/latest/api/dates.html
humanize is apparently a human-readable directioned delta, so that'd be format_timedelta(delta, add_direction=True)
>>> print format_timedelta(ref - datetime.now(), add_direction=True)
1 hour ago
>>> print format_timedelta(ref - datetime.now(), add_direction=True, locale='zh')
1小时前
>>> print format_timedelta(ref - datetime.now(), add_direction=True, locale='ru')
1 час назадI think Delorean, Pendulum, Arrow, etc, aim to make dealing with dates more understandable and less painful. It's perfectly possible to fully grasp all the technicalities of pytz/dateutil/datetime -- and I recommend that anybody who has to deal with dates and times in Python do so -- but if you'd rather not think about it all and are okay with deferring some control to the opinions of one of these libraries, that's when you probably pull them off the shelf instead of the aforementioned trio.
Also, Pendulum is not just about datetimes but also provides both the Interval class and Period class which are improvements over the native timedelta class.
And finally, it handles properly time shifting around DST transition times and normalization of datetimes when creating them which neither Delorean nor Arrow do well.
Not saying storing user timezone and converting on the backend is bad; but this is simpler when localized timestamps aren't a core part of my app.
If a Samoan user told you to record an event for January 1st 2012 on January 1st 2011, if you stored the date in UTC would have reminded them on January 2nd 2012 (all local).
Because in May 2011 Samoa announced they were going to skip a local day and move across the international date line. So 2011-12-30T09:00:00 UTC was 2011-12-29T23:00:00 Pacific/Apia, but 2011-12-30T10:00:00 UTC was 2011-12-31T00:00:00 Pacific/Apia.
Yep, or if a DST change was added or rescinded (which can happen on surprisingly short orders, many governments love fucking up with DST, this year 2016 we got an infirmation of Egyptian DST with 3 days lead time).
Anybody know of an elegant solution/library or even a library that would be open to including such a concept?
Eg, spot the error:
_weekend_days = [SATURDAY, SUNDAY]
date.is_weekend = date.day in _weekend_days
Hint: https://en.wikipedia.org/wiki/Workweek_and_weekend#Around_th...(TIL one country doesn't even have consecutive weekend days)
pendulum.set_weekend_days([pendulum.SUNDAY])I think the `in_words()` function should probably be delimited by commas though, good to have your strings easily deconstructed into their constituent parts.