Package: pymoment
pymomentThe python version of "moment" which is made with reference to "moment.js"To install pymoment, please download the whl file, then install with thepipcommand:pip install pymoment-*.whlor just install:pip install pymomentThen import the package for your code:from moment import momentParameter for ConstructorCodeNotesNonemoment()Get the current date and timemomentmoment(m)Create a new moment object with the moment object "m"datetime.datetimemoment(d)Create a moment object with the datetime object "d"strmoment('2021-04-12')Parsing the string to a moment objectlistmoment([2021, 4, 12])Parsing the list to a moment objectParseNownow = moment()now = moment([])now = moment(datetime.datetime.now())Stringmoment(String)You can create a moment from a string. The following are examples of strings in supported formats.2013-02-08               # Date only2013-02-08T09            # An hour time part separated by a T2013-02-08 09            # An hour time part separated by a space2013-02-08 09:30         # An hour and minute time part2013-02-08 09:30:26      # An hour, minute, and second time part2013-02-08 09:30:26.123  # An hour, minute, second, and millisecond time part20130208T080910,123      # Short date and time up to ms, separated by comma20130208T080910.123      # Short date and time up to ms20130208T080910          # Short date and time up to seconds20130208T0809            # Short date and time up to minutes20130208T08              # Short date and time, hours only20130208                 # Short date onlyWith time zone:2021-04-22 04:02:09.957000 +08002021-04-22 04:02:09 +08002021-04-22 04:02 +08002021-04-22 04 +080020210422 04:02:09 +0800Listmoment([2021, 4, 12])You can create a moment with a list of numbers that mirror the parameters passed to datetime.[ year, month=1, day=1, hour=0, minute=0, second=0, microsecond=0 ]Any parameter except "year" will default to the lowest possible number.moment([2010])        # January 1stmoment([2010, 6])     # July 1stmoment([2010, 6, 10]) # July 10thIf an empty list is passed, you could get the current date time.moment([])DisplayOnce parsing and manipulation are done, you need some way to display the moment.FormatThis is the most robust display option. It takes a string of tokens and replaces them with their corresponding values.moment().format()moment().format(String)TokenOutputMonthM1 2 ... 11 12Mo1st 2nd ... 11th 12thMM01 02 ... 11 12MMMJan Feb ... Nov DecMMMMJanuary February ... November DecemberQuarterQ1 2 3 4Qo1st 2nd 3rd 4thDay of MonthD1 2 ... 30 31Do1st 2nd ... 30th 31stDD01 02 ... 30 31Day of YearDDD1 2 ... 364 365DDDo1st 2nd ... 364th 365thDDDD001 002 ... 364 365Day of Weekd0 1 ... 5 6do0th 1st ... 5th 6thddSu Mo ... Fr SadddSun Mon ... Fri SatddddSunday Monday ... Friday SaturdayDay of Week (ISO)E1 2 ... 6 7Week of Yearw1 2 ... 52 53wo1st 2nd ... 52nd 53rdww01 02 ... 52 53Week of Year (ISO)W1 2 ... 52 53Wo1st 2nd ... 52nd 53rdWW01 02 ... 52 53YearYY70 71 ... 29 30YYYY1970 1971 ... 2029 2030AM/PMAAM PMaam pmHourH0 1 ... 22 23HH00 01 ... 22 23h1 2 ... 11 12hh01 02 ... 11 12k1 2 ... 23 24kk01 02 ... 23 24Minutem0 1 ... 58 59mm00 01 ... 58 59Seconds0 1 ... 58 59ss00 01 ... 58 59Fractional SecondS0 1 ... 8 9SS00 01 ... 98 99SSS000 001 ... 998 999SSSS0000 0001 ... 9998 9999SSSSS00000 00001 ... 99998 99999SSSSSS000000 000001 ... 999998 999999Time ZoneZ-07:00 -06:00 ... +06:00 +07:00ZZ-0700 -0600 ... +0600 +0700Unix TimestampX1360013296Unix Millisecond Timestampx1360013296123TimeLT8:30 PMTime with secondsLTS8:30:25 PMMonth numeral, day of month, yearL09/04/1986l9/4/1986Month name, day of month, yearLLSeptember 4, 1986llSep 4, 1986Month name, day of month, year, timeLLLSeptember 4, 1986 8:30 PMlllSep 4, 1986 8:30 PMMonth name, day of month, day of week, year, timeLLLLThursday, September 4, 1986 8:30 PMllllThu, Sep 4, 1986 8:30 PMEscaping charactersTo escape characters in format strings, you can wrap the characters in square brackets.moment('2021-04-22 04:02:09.957000 +0800').format('[Today is] dddd.')'Today is Thursday.'Get + SetCalling all methods without parameters acts as a getter, and calling them with a parameter acts as a setter.Millisecondmoment().millisecond(Number)moment().millisecond()  # Numbermoment().milliseconds(Number)moment().milliseconds()  # NumberGets or sets the milliseconds.Accepts numbers from 0 to 999. If the range is exceeded, it will bubble up to the seconds.Secondmoment().second(Number)moment().second()  # Numbermoment().seconds(Number)moment().seconds()  # NumberGets or sets the seconds.Accepts numbers from 0 to 59. If the range is exceeded, it will bubble up to the minutes.Minutesmoment().minute(Number)moment().minute()  # Numbermoment().minutes(Number)moment().minutes()  # NumberGets or sets the minutes.Accepts numbers from 0 to 59. If the range is exceeded, it will bubble up to the hour.Hourmoment().hour(Number)moment().hour()  # Numbermoment().hours(Number)moment().hours()  # NumberGets or sets the hour.Accepts numbers from 0 to 23. If the range is exceeded, it will bubble up to the day.Date of Monthmoment().date(Number)moment().date()  # Numbermoment().dates(Number)moment().dates()  # NumberGets or sets the day of the month.Accepts numbers from 1 to 31. If the range is exceeded, it will bubble up to the months.Note:moment.dateis for the date of the month, andmoment.dayis for the day of the week.Day of Weekmoment().day(Number)moment().day()  # Numbermoment().days(Number)moment().days()  # NumberGets or sets the day of the week.This method can be used to set the day of the week, with Sunday as 0 and Saturday as 6.If the value given is from 0 to 6, the resulting date will be within the current (Sunday-to-Saturday) week.If the range is exceeded, it will bubble up to other weeks.Note:moment.dateis for the date of the month, andmoment.dayis for the day of the week.Day of Week (Locale Aware)moment().weekday(Number)moment().weekday()  # Numbermoment().weekday(Number)moment().weekday() # NumberGets or sets the day of the week according to the locale.If the locale assigns Monday as the first day of the week, moment().weekday(0) will be Monday. If Sunday is the first day of the week, moment().weekday(0) will be Sunday.Day of Week (Locale Aware)moment().isoWeekday(Number)
moment().isoWeekday()  # NumberGets or sets the ISO day of the week with 1 being Monday and 7 being Sunday.As with moment#day, if the range is exceeded, it will bubble up to other weeks.Day of Yearmoment().dayOfYear(Number)moment().dayOfYear()  # NumberGets or sets the day of the year.Accepts numbers from 1 to 366. If the range is exceeded, it will bubble up to the years.Week of Yearmoment().week(Number)moment().week()  # Numbermoment().weeks(Number)moment().weeks()  # NumberGets or sets the week of the year.Because different locales define week of year numbering differently, usemoment.localto set the localized week of the year.The week of the year varies depending on which day is the first day of the week (Sunday, Monday, etc), and which week is the first week of the year.For example, in the United States, Sunday is the first day of the week. The week with January 1st in it is the first week of the year.In France, Monday is the first day of the week, and the week with January 4th is the first week of the year.The output ofmoment.weekwill depend on the locale for that moment.When setting the week of the year, the day of the week is retained.Week of Year (ISO)moment().isoWeek(Number)moment().isoWeek()  # Numbermoment().isoWeeks(Number)moment().isoWeeks()  # NumberGets or sets theISO week of the year.When setting the week of the year, the day of the week is retained.Monthmoment().month(Number)moment().month()  # Numbermoment().months(Number)moment().months()  # NumberGets or sets the month.Accepts numbers from 0 to 11. If the range is exceeded, it will bubble up to the year.Note: Months are zero indexed, so January is month 0.Quartermoment().quarter()  # Numbermoment().quarter(Number)moment().quarters()  # Numbermoment().quarters(Number)Gets the quarter (1 to 4) and sets the quarter with parameterNumber.If the range is exceeded, it will bubble up to other quarters.Yearmoment().year(Number)moment().year()  # Numbermoment().years(Number)moment().years()  # NumberGets or sets the year. According todatetime.MINYEAR, parameterNumbershould larger than zero.Weeks In Yearmoment().weeksInYear()Gets the number of weeks according to locale in the current moment's year.Weeks In Year (ISO)moment().isoWeeksInYear()Gets the number of weeks in the current moment's year, according toISO weeks.Unix Timestampmoment().unix()moment.unixoutputs a Unix timestamp (the number of seconds since the Unix Epoch).This value is floored to the nearest second, and does not include a milliseconds component.Days in Monthmoment().daysInMonth()Get the number of days in the current month.moment('20200213').daysInMonth()  # 29moment('20210813').daysInMonth()  # 31Days in Yearmoment().daysInYear()Get the number of days in the current year.moment('20200213').daysInYear()  # 366moment('20210413').daysInYear()  # 365ManipulateAddmoment().add(Number, String, inplace=False)moment().add(Dictionary)Mutates the original moment by adding time and return a new moment instance as a result.This is a pretty robust function for adding time to an existing moment. To add time, pass the key of what time you want to add, and the amount you want to add.moment().add(7, 'days')moment().add({'days': 7})There are some shorthand keys as well if you're into that whole brevity thing.moment().add(7, 'd')moment().add({'d': 7})IfinplaceisTrue, the original moment instance should be updated by the adding operation.KeyShorthandyearsyquartersQmonthsMweekswdaysdhourshminutesmsecondssmillisecondsmsIf the day of the month on the original date is greater than the number of days in the final month, the day of the month will change to the last day in the final month.moment('2010-01-31').add(1, 'months') # 2010-02-28When decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.moment('2010-01-31').add(1.5, 'months') == moment('2010-01-31').add(2, 'months')moment('2010-01-31').add(.7, 'years') == moment('2010-01-31').add(8, 'months') # .7*12 = 8.4, rounded to 8Subtractmoment().subtract(Number, String, inplace=False)moment().subtract(Dictionary)Mutates the original moment by subtracting time and return a new moment instance as a result.This is exactly the same asmoment().add, only instead of adding time, it subtracts time.moment().subtract(7, 'days')moment().subtract({'days': 7})IfinplaceisTrue, the original moment instance should be updated by the subtracting operation.Start of Timemoment().startOf(String, inplace=False)Mutates the original moment by setting it to the start of a unit of time.IfinplaceisTrue, the original moment instance should be updated to the start of a unit of time.moment().startOf('year')     # set to January 1st, 12:00 am this yearmoment().startOf('month')    # set to the first of this month, 12:00 ammoment().startOf('quarter')  # set to the beginning of the current quarter, 1st day of months, 12:00 ammoment().startOf('week')     # set to the first day of this week, 12:00 ammoment().startOf('isoWeek')  # set to the first day of this week according to ISO 8601, 12:00 ammoment().startOf('day')      # set to 12:00 am todaymoment().startOf('date')     # set to 12:00 am todaymoment().startOf('hour')     # set to now, but with 0 mins, 0 secs, and 0 msmoment().startOf('minute')   # set to now, but with 0 seconds and 0 millisecondsmoment().startOf('second')   # same as moment().milliseconds(0)End of Timemoment().endOf(String, inplace=False)Mutates the original moment by setting it to the end of a unit of time.This is the same asmoment.startOf, only instead of setting to the start of a unit of time, it sets to the end of a unit of time.Operator"+" and "-" are supported.While doing "-" operation,timedeltais the result of the operation.(moment('20201228') - moment('20201225')) == timedelta(days=3)While doing "+" operation,timedeltais added to the moment instance and returning a new moment instance.The followings should get the same result.moment('20201228') + timedelta(days=3)moment('20201228').add(3, 'd')QueryIs Beforemoment().isBefore(moment|str|datetime|list)moment().isBefore(moment|str|datetime|list, str)moment().isBefore(moment|str|datetime|list, str, bool)Check if a moment is before another moment. The first argument will be parsed as a moment, if not already so.moment('2010-10-20').isBefore('2010-10-21')  # TrueIf the unit is passed as the second parameter, and the start of a unit of time or the end of a unit of time would be used to be compared.The third parameter is used to determine usingstartOforendOftime of the moment instance. Default isFalsewhich means usingendOftime of the moment instance.moment('2010-10-20').isBefore('2010-12-31', 'year')  # Falsemoment('2010-10-20').isBefore('2010-12-31', 'year', True)  # TrueLikemoment.isAfterandmoment.isSame, any of the units of time that are supported formoment.startOfare supported formoment.isBefore.year quarter month week isoWeek day date hour minute secondIs Samemoment().isSame(moment|str|datetime|list)moment().isSame(moment|str|datetime|list, str)moment().isSame(moment|str|datetime|list, str, bool)Check if a moment is the same as another moment. The first argument will be parsed as a moment, if not already so.moment('2010-10-20').isSame('2010-10-20')  # TrueLikemoment.isBefore, if the unit is passed as the second parameter, and the start of a unit of time or the end of a unit of time would be used to be compared.The third parameter is used to determine usingstartOforendOftime of the moment instance. Default isFalsewhich means usingendOftime of the moment instance.Is Aftermoment().isAfter(moment|str|datetime|list)moment().isAfter(moment|str|datetime|list, str)moment().isAfter(moment|str|datetime|list, str, bool)Check if a moment is after another moment. The first argument will be parsed as a moment, if not already so.moment('2010-10-20').isAfter('2010-10-19')  # TrueLikemoment.isBefore, if the unit is passed as the second parameter, and the start of a unit of time or the end of a unit of time would be used to be compared.The third parameter is used to determine usingstartOforendOftime of the moment instance. Default isFalsewhich means usingendOftime of the moment instance.Is Same or Beforemoment().isSameOrBefore(moment|str|datetime|list)moment().isSameOrBefore(moment|str|datetime|list, str)moment().isSameOrBefore(moment|str|datetime|list, str, bool)Check if a moment is before or the same as another moment. The first argument will be parsed as a moment, if not already so.moment('2010-10-20').isSameOrBefore('2010-10-21')  # Truemoment('2010-10-20').isSameOrBefore('2010-10-20')  # Truemoment('2010-10-20').isSameOrBefore('2010-10-19')  # TrueLikemoment.isBefore, if the unit is passed as the second parameter, and the start of a unit of time or the end of a unit of time would be used to be compared.The third parameter is used to determine usingstartOforendOftime of the moment instance. Default isFalsewhich means usingendOftime of the moment instance.a = moment('2021-04-22 04:02:09.957000 +0800')b = moment('2021-2-2 13:02:09.957000 +0800')a.isSameOrBefore(b, 'year')  # Falsea.isSameOrBefore(b, 'year', True)  #TrueIs Same or Aftermoment().isSameOrAfter(moment|str|datetime|list)moment().isSameOrAfter(moment|str|datetime|list, str)moment().isSameOrAfter(moment|str|datetime|list, str, bool)Check if a moment is after or the same as another moment. The first argument will be parsed as a moment, if not already so.moment('2010-10-20').isSameOrAfter('2010-10-19')  # Truemoment('2010-10-20').isSameOrAfter('2010-10-20')  # Truemoment('2010-10-20').isSameOrAfter('2010-10-21')  # FalseLikemoment.isBefore, if the unit is passed as the second parameter, and the start of a unit of time or the end of a unit of time would be used to be compared.The third parameter is used to determine usingstartOforendOftime of the moment instance. Default isFalsewhich means usingendOftime of the moment instance.a = moment('2021-04-22 04:02:09.957000 +0800')b = moment('2021-2-2 13:02:09.957000 +0800')a.isSameOrAfter(b, 'year')  # Truea.isSameOrAfter(b, 'year', True)  # False###Is Betweenmoment().isBetween(moment|str|datetime|list, moment|str|datetime|list)moment().isBetween(moment|str|datetime|list, moment|str|datetime|list, str)moment().isBetween(moment|str|datetime|list, moment|str|datetime|list, str, bool)Check if a moment is between two other moments, optionally looking at unit scale (minutes, hours, days, etc). The match is exclusive. The first two arguments will be parsed as moments, if not already so.moment('2010-10-20').isBetween('2010-10-19', '2010-10-25')  # TrueNote that the order of the two argumentsdo notmatter.moment('2010-10-20').isBetween('2010-10-19', '2010-10-25')  # Truemoment('2010-10-20').isBetween('2010-10-25', '2010-10-19')  # TrueLikemoment.isBefore, if the unit is passed as the second parameter, and the start of a unit of time or the end of a unit of time would be used to be compared.The third parameter is used to determine usingstartOforendOftime of the moment instance. Default isFalsewhich means usingendOftime of the moment instance.a = moment('20210426')b = moment('20210429')c = moment('20210502')a.isBetween(b, c, 'week')  # Trueb.isBetween(a, c, 'week', True)  # FalseIs Leap Yearmoment().isLeapYear()moment().isLeap()moment.isLeapYearandmoment.isLeapreturn true if that year is a leap year, and false if it is not.moment([2020]).isLeapYear()  # Truemoment([2020]).isLeap()  # Truemoment([2021]).isLeap()  # FalseCustomizeFirst Day of Week and First Week of Yearweek = { 'dow': int, 'doy': int }moment().locale(week)week['dow']should be an integer representing the first day of the week, 0 is Sunday, 1 is Monday, ..., 6 is Saturday. Default is 0.week['doy']should be an integer.doyis used together withdowto determine the first week of the year.doyis calculated as7 + dow - janX, wherejanXis the first day of January that must belong to the first week of the year. Default is 6.