A Python library for dealing with dates

Overview

moment

A Python library for dealing with dates/times. Inspired by Moment.js and Kenneth Reitz's Requests library. Ideas were also taken from the Times Python module.

Installation

I would advise that this is beta-quality software. You might be interested in:

Still want to use moment?

pip install moment

Usage

import moment
from datetime import datetime

# Create a moment from a string
moment.date("12-18-2012")

# Create a moment with a specified strftime format
moment.date("12-18-2012", "%m-%d-%Y")

# Moment uses the awesome dateparser library behind the scenes
moment.date("2012-12-18")

# Create a moment with words in it
moment.date("December 18, 2012")

# Create a moment that would normally be pretty hard to do
moment.date("2 weeks ago")

# Create a moment from the current datetime
moment.now()

# The moment can also be UTC-based
moment.utcnow()

# Create a moment with the UTC time zone
moment.utc("2012-12-18")

# Create a moment from a Unix timestamp
moment.unix(1355875153626)

# Create a moment from a Unix UTC timestamp
moment.unix(1355875153626, utc=True)

# Return a datetime instance
moment.date(2012, 12, 18).date

# We can do the same thing with the UTC method
moment.utc(2012, 12, 18).date

# Create and format a moment using Moment.js semantics
moment.now().format("YYYY-M-D")

# Create and format a moment with strftime semantics
moment.date(2012, 12, 18).strftime("%Y-%m-%d")

# Use the special `%^` combo to add a date suffix (1st, 2nd, 3rd, 4th, etc)
moment.date(2012, 12, 18).strftime("%B %-d%^, %Y")

# Update your moment's time zone
moment.date(datetime(2012, 12, 18)).locale("US/Central").date

# Alter the moment's UTC time zone to a different time zone
moment.utcnow().timezone("US/Eastern").date

# Set and update your moment's time zone. For instance, I'm on the
# west coast, but want NYC's current time.
moment.now().locale("US/Pacific").timezone("US/Eastern")

# In order to manipulate time zones, a locale must always be set or
# you must be using UTC.
moment.utcnow().timezone("US/Eastern").date

# You can also clone a moment, so the original stays unaltered
now = moment.utcnow().timezone("US/Pacific")
future = now.clone().add(weeks=2)

Chaining

Moment allows you to chain commands, which turns out to be super useful.

# Customize your moment by chaining commands
moment.date(2012, 12, 18).add(days=2).subtract(weeks=3).date

# Imagine trying to do this with datetime, right?
moment.utcnow().add(years=3, months=2).format("YYYY-M-D h:m A")

# You can use multiple keyword arguments
moment.date(2012, 12, 19).add(hours=1, minutes=2, seconds=3)

# And, a similar subtract example...
moment.date(2012, 12, 19, 1, 2, 3).subtract(hours=1, minutes=2, seconds=3)

# In addition to adding/subtracting, we can also replace values
moment.now().replace(hours=5, minutes=15, seconds=0).epoch()

# And, if you'd prefer to keep the microseconds on your epoch value
moment.now().replace(hours=5, minutes=15, seconds=0).epoch(rounding=False)

# Years, months, and days can also be set
moment.now().replace(years=1984, months=1, days=1, hours=0, minutes=0, seconds=0)

# Also, datetime properties are available
moment.utc(2012, 12, 19).year == 2012

# Including plural ones (since I'm bad at remembering)
moment.now().seconds

# We can also manipulate to preferred weekdays, such as Monday
moment.date(2012, 12, 19).replace(weekday=1).strftime("%Y-%m-%d")

# Or, this upcoming Sunday
moment.date("2012-12-19").replace(weekday=7).date

# We can even go back to two Sundays ago
moment.date(2012, 12, 19).replace(weekday=-7).format("YYYY-MM-DD")

# It's also available as a property
moment.utcnow().weekday

# And, there's an easy way to zero out the hours, minutes, and seconds
moment.utcnow().zero
Comments
  • Python 3 support

    Python 3 support

    Hi.

    I've been trying to use Moment with Python 3.4 and got this:

    In [1]: import moment
    
    In [2]: moment.now().subtract(monthes=6)
    
    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-2-9407b0856ff3> in <module>()
    ----> 1 moment.now().subtract(monthes=6)
    
    /usr/lib/python3.4/site-packages/moment/date.py in subtract(self, key, amount, **kwds)
         65         """Subtract time from the original moment."""
         66         if not key and not amount and len(kwds):
    ---> 67             for k, v in kwds.iteritems():
         68                 self.subtract(k, v)
         69         if key == 'years' or key == 'year':
    
    AttributeError: 'dict' object has no attribute 'iteritems'
    
    opened by naquad 3
  • Use ISO format for `repr` representation

    Use ISO format for `repr` representation

    String provided by repr of date is misleading:

    >>> import moment
    >>> m = moment.date("11-12-2012", "M-D-YYYY")
    >>> repr(m)
    '<Moment(11-12-2012)>'
    >>> m2 = moment.date("11-12-2012", "D-M-YYYY")
    >>> repr(m2)
    '<Moment(11-12-2012)>'
    >>> m.date
    datetime.datetime(2012, 11, 12, 0, 0)
    >>> m2.date
    datetime.datetime(2012, 12, 11, 0, 0)
    

    As you see, while the dates are different, strings returned are equal:

    >>> m == m2
    False
    >>> repr(m) == repr(m2)
    True
    

    This is against convention, that repr tries to represent the value as precisely as possible.

    Proposal: print the value as ISO formatted string.

    opened by vlcinsky 3
  • invalid result in `moment.subtract`

    invalid result in `moment.subtract`

    $ pip3 freeze | grep moment
    moment==0.10
    
    >>> import moment
    >>> import datetime
    >>> moment.date(datetime.date(2020, 1, 1)).subtract(months=1).isoformat()
    '2020-12-01'
    

    was expecting 2019-01-01

    bug 
    opened by nkanaev 2
  • Parsing a year creates a date in the 1st of July

    Parsing a year creates a date in the 1st of July

    Is it a bug or undocumented feature? Not sure if I understand it. Thanks in advance.

    In [1]: import moment
    
    In [2]: moment.date('2000').date
    Out[2]: datetime.datetime(2000, 7, 1, 0, 0)
    
    opened by msamoylov 2
  • Use tox

    Use tox

    Set out to fix the deprecated pip install --use-mirrors but ended up introducing tox to test against multiple versions of python and have travis use this.

    opened by shanx 2
  • type error when using add method

    type error when using add method

    When I use something like moment.utcnow().add(years=3, months=2).format("YYYY-M-D h:m A") i get a type error that says integer argument expected, got float. How should I go about resolving this issue? I have tried a couple of things, but couldn't seem to get it to work as expected.

    opened by dsikes 2
  • Allow specifying the format/locale for month and day display

    Allow specifying the format/locale for month and day display

    Hello,

    I need to parse dates easily with different formats and moment is amazing for this, and I thank you very much for your work!

    As you may or may not know, the US always does stuff differently than the rest of the world and, for example, display their dates month first (which IMO makes no sense) but makes it a hassle for parsing.

    See my example here:

    >>> moment.date("11/05/2022").strftime("Month: %m, Day: %d, Year: %Y")
    'Month: 11, Day: 05, Year: 2022'
    

    Whereas I would've expected it to output the 11th of May... I tried using the .locale() method but it didn't fix it. Any idea ?

    opened by Seluj78 1
  • epoch does not return the same Unix Timestamp

    epoch does not return the same Unix Timestamp

    moment.unix(t).epoch() does not equal t.

    t = 1653430533339. # GMT: Tuesday, May 24, 2022 10:15:33.339 PM moment.unix(t).epoch(). # 1653405333 -> GMT: Tuesday, May 24, 2022 3:15:33 PM

    image
    opened by byukan 1
  • Incorrect Results for Parssing Data Time

    Incorrect Results for Parssing Data Time

    Hi, I am a high school student just starting to learn about testing techniques. I found a bug in the latest version (0.12.1) of moment while doing some fuzzing using the fuzzing tool Atheris. The reproducing process is shown below:

    import moment
    moment.date('2001W5')
    

    Results <Moment(1984-01-03T17:32:28)>

    My Environment

    Python 3.8.10 (default, Mar 15 2022, 12:22:08) 
    [GCC 9.4.0] on linux 
    moment in /home/clou5/.local/lib/python3.8/site-packages (0.12.1)
    

    I am still not very sure about the bug so I would very much appreciate any kind of feedback regarding it. Thanks.

    opened by OrianeK 1
  • how can i use moment diff get a seconds measurement result

    how can i use moment diff get a seconds measurement result

    @classmethod def diff(cls, start_time: Moment, end_time: Moment, diff_type=None): if not diff_type: diff_type = 'seconds' start = cls.get_current_moment(start_time) end = cls.get_current_moment(end_time) return end.diff(start)

    opened by Jakin-Liu 1
  • TypeError: unsupported operand type(s) for +=: 'int' and 'datetime.timedelta'

    TypeError: unsupported operand type(s) for +=: 'int' and 'datetime.timedelta'

    This method fails:

    moment.date(time_delta).add(weeks=week_range)

    And returns this error:

      File "C:\Python39\lib\site-packages\moment\date.py", line 50, in add
        self.add(k, v)
      File "C:\Python39\lib\site-packages\moment\date.py", line 56, in add
        self._date += timedelta(weeks=amount)
    TypeError: unsupported operand type(s) for +=: 'int' and 'datetime.timedelta'
    
    opened by salinaaaaaa 1
  • Conflict timezone results with datetime

    Conflict timezone results with datetime

    (venv) wangchengjie@wangchengjies-iMac coverity % python --version   
    Python 3.6.8
    

    The below code produced conflict results when I compared it with datetime

        from moment import Moment, now
        a = now()
        print(a)
        a.timezone('America/Los_Angeles')
        print(a)
        from datetime import datetime
        from dateutil import tz, zoneinfo
        tz_pst = tz.gettz('America/Los_Angeles')
        print(datetime.now())
        d = datetime.now(tz=tz_pst)
        print(d)
    

    output:

    2022-03-15T03:30:45+08.00
    2022-03-14T20:30:45+08.00
    2022-03-15 03:30:45.220210
    2022-03-14 12:30:45.220222-07:00
    
    opened by veictry 4
  • Error on .add method

    Error on .add method

    There is a recursive error (probably on line 60 of file moment/date.py you have to return in order to avoid the replication of the operation). I add to you two examples, the first shows the error with moment, the second abstracts the error in a python primitive way.

    import moment
    
    start = moment.date('2021-12-01T18:49:25.902586+0000').locale('utc')
    
    print(start.add(days=30).datetime)
    
    class Tester:
    
        def __init__(self):
            self.ab = 1
    
        def test(self, i=0):
            if i == 0:
                for x in ['test']:
                    self.test(i=1)
    
            self.ab += 1
    
            return self
    
    
    t = Tester()
    
    print(t.test().ab)
    

    I used "probably" above because the problem seems to appear and disappear without any logic.

    Screenshot_code
    opened by LuckyExplorer88 1
Owner
Zach Williams
πŸ€πŸ“Š
Zach Williams
Friendly Python Dates

When.py: Friendly Dates and Times Production: Development: User-friendly functions to help perform common date and time actions. Usage To get the syst

Andy Dirnberger 191 Oct 14, 2022
Better dates & times for Python

Arrow: Better dates & times for Python Arrow is a Python library that offers a sensible and human-friendly approach to creating, manipulating, formatt

Arrow 8.2k Jan 5, 2023
python parser for human readable dates

Python parser for human readable dates Key Features β€’ How To Use β€’ Installation β€’ Common use cases β€’ You may also like... β€’ License Key Features Suppo

Scrapinghub 2.2k Jan 8, 2023
A simple in-process python scheduler library, designed to be integrated seamlessly with the `datetime` standard library.

scheduler A simple in-process python scheduler library, designed to be integrated seamlessly with the datetime standard library. Due to the support of

null 30 Dec 30, 2022
pytz Python historical timezone library and database

pytz Brings the IANA tz database into Python. This library allows accurate and cross platform timezone calculations. pytz contains generated code, and

Stub 236 Jan 3, 2023
darts is a Python library for easy manipulation and forecasting of time series.

A python library for easy manipulation and forecasting of time series.

Unit8 5.2k Jan 1, 2023
Useful extensions to the standard Python datetime features

dateutil - powerful extensions to datetime The dateutil module provides powerful extensions to the standard datetime module, available in Python. Inst

null 2k Dec 29, 2022
Python datetimes made easy

Pendulum Python datetimes made easy. Supports Python 2.7 and 3.4+. >>> import pendulum >>> now_in_paris = pendulum.now('Europe/Paris') >>> now_in_par

SΓ©bastien Eustace 5.3k Jan 6, 2023
PyTime is an easy-use Python module which aims to operate date/time/datetime by string.

PyTime PyTime is an easy-use Python module which aims to operate date/time/datetime by string. PyTime allows you using nonregular datetime string to g

Sinux 148 Dec 9, 2022
Generate and work with holidays in Python

python-holidays A fast, efficient Python library for generating country, province and state specific sets of holidays on the fly. It aims to make dete

Maurizio Montel 881 Dec 29, 2022
A Python module that tries to figure out what your local timezone is

tzlocal This Python module returns a tzinfo object with the local timezone information under Unix and Windows. It requires either Python 3.9+ or the b

Lennart Regebro 159 Dec 16, 2022
Make Python datetime formatting human readable

Make Python datetime formatting human readable

James Timmins 0 Oct 3, 2021
A simple digital clock made with the help of python

Digital-Clock ⏰ Description ?? βœ”οΈ A simple digital clock made with the help of python. The code is easy to understand and implement. With this reposit

Mohit 0 Dec 10, 2021
A datetime parser in Python by Ari24-cb24 and NekoFantic

datetimeparser A datetime parser in Python by Ari24-cb24 and NekoFantic V 1.0 Erinnerung fΓΌr den Parser Auf falsche Eingaben ΓΌberprΓΌfen Liste an Event

AriDevelopment 13 Dec 30, 2022
Fully Automated YouTube Channel ▢️with Added Extra Features.

Fully Automated Youtube Channel β–’β–ˆβ–€β–€β–ˆ β–ˆβ–€β–€β–ˆ β–€β–€β–ˆβ–€β–€ β–€β–€β–ˆβ–€β–€ β–ˆβ–‘β–‘β–ˆ β–ˆβ–€β–€β–„ β–ˆβ–€β–€ β–ˆβ–€β–€β–ˆ β–’β–ˆβ–€β–€β–„ β–ˆβ–‘β–‘β–ˆ β–‘β–‘β–ˆβ–‘β–‘ β–‘β–’β–ˆβ–‘β–‘ β–ˆβ–‘β–‘β–ˆ β–ˆβ–€β–€β–„ β–ˆβ–€β–€ β–ˆβ–„β–„β–€ β–’β–ˆβ–„β–„β–ˆ β–€β–€β–€β–€ β–‘β–‘β–€β–‘β–‘ β–‘β–’β–ˆβ–‘β–‘ β–‘β–€β–€β–€ β–€β–€β–€β–‘

sam-sepiol 249 Jan 2, 2023
statDistros is a Python library for dealing with various statistical distributions

StatisticalDistributions statDistros statDistros is a Python library for dealing with various statistical distributions. Now it provides various stati

null 1 Oct 3, 2021
AuthGG is a Python library for dealing with Auth.gg apis

AuthGG AuthGG is a Python library for dealing with Auth.gg apis Installation Use the package manager pip to install requests Add the auth.py file in y

ExtremeDev 1 Dec 20, 2021
Practice-python is a simple Fast api project for dealing with modern rest api technologies.

Practice Python Practice-python is a simple Fast api project for dealing with modern rest api technologies. Deployment with docker Go to the project r

null 0 Sep 19, 2022
Bypass ReCaptcha: A Python script for dealing with recaptcha

Bypass ReCaptcha Bypass ReCaptcha is a Python script for dealing with recaptcha.

Marcos Camargo 1 Jan 11, 2022
PyBeacon is a collection of scripts for dealing with Cobalt Strike's encrypted traffic.

PyBeacon is a collection of scripts for dealing with Cobalt Strike's encrypted traffic. It can encrypt/decrypt beacon metadata, as well as pa

NCC Group Plc 162 Dec 21, 2022