nepali_datetime
— Bikram Sambat Date and Nepal Time types¶
The nepali_datetime
module is highly motivated from the Python3’s
datetime
module. The module supplies classes for manipulating
Bikram Sambat dates and Nepal times in both simple and complex ways.
The nepali_datetime
module exports the following constants:
- nepali_datetime.MINYEAR¶
The smallest year number allowed in a
date
ordatetime
object.MINYEAR
is1975
.
- nepali_datetime.MAXYEAR¶
The largest year number allowed in a
date
ordatetime
object.MAXYEAR
is2100
.
- nepali_datetime.NEPAL_TIME_UTC_OFFSET¶
The UTC offset of Nepal time
+05:45
.
Available Types¶
- class nepali_datetime.date
An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect. Attributes:
year
,month
, andday
.
- class nepali_datetime.UTC0545¶
A
tzinfo
subclass for Nepal timezone.
nepali_datetime.date
Objects¶
A date
object represents a date (year, month and day) in B.S calendar. Baishak 1 of year 1975 is called day
number 1, Baishak 2 of year 1975 is called day number 2, and so on.
- class nepali_datetime.date(year, month, day)¶
All arguments are required. Arguments may be integers, in the following ranges:
MINYEAR <= year <= MAXYEAR
1 <= month <= 12
1 <= day <= number of days in the given month and year
If an argument outside those ranges is given,
ValueError
is raised.
Other constructors, all class methods:
- classmethod date.today()¶
Return the current B.S date.
- classmethod date.from_datetime_date(datetime.date)¶
Return the converted
nepalidatetime.date
(B.S) object for the givendatetime.date
object.Example:
>>> import datetime >>> import nepali_datetime >>> dt = datetime.date(2018, 11, 7) >>> nepali_datetime.date.from_datetime_date(dt) nepali_datetime.date(2075, 7, 21)
Class attributes:
- date.min¶
The earliest representable date,
date(MINYEAR, 1, 1)
.
- date.max¶
The latest representable date,
date(MAXYEAR, 12, MAXYEAR_LAST_MONTHS_LAST_DAY)
.
- date.resolution¶
The smallest possible difference between non-equal date objects,
timedelta(days=1)
.
Instance attributes (read-only):
- date.month¶
Between 1 and 12 inclusive.
- date.day¶
Between 1 and the number of days in the given month of the given year.
Supported operations:
Operation |
Result |
---|---|
|
date2 is |
|
Computes date2 such that |
|
(3) |
|
date1 is considered less than date2 when date1 precedes date2 in time. (4) |
Notes:
date2 is moved forward in time if
timedelta.days > 0
, or backward iftimedelta.days < 0
. Afterwarddate2 - date1 == timedelta.days
.timedelta.seconds
andtimedelta.microseconds
are ignored.OverflowError
is raised ifdate2.year
would be smaller thanMINYEAR
or larger thanMAXYEAR
.This isn’t quite equivalent to date1 + (-timedelta), because -timedelta in isolation can overflow in cases where date1 - timedelta does not.
timedelta.seconds
andtimedelta.microseconds
are ignored.This is exact, and cannot overflow. timedelta.seconds and timedelta.microseconds are 0, and date2 + timedelta == date1 after.
In other words,
date1 < date2
if and only ifdate1.toordinal() < date2.toordinal()
. In order to stop comparison from falling back to the default scheme of comparing object addresses, date comparison normally raisesTypeError
if the other comparand isn’t also adate
object. However,NotImplemented
is returned instead if the other comparand has atimetuple()
attribute. This hook gives other kinds of date objects a chance at implementing mixed-type comparison. If not, when adate
object is compared to an object of a different type,TypeError
is raised unless the comparison is==
or!=
. The latter cases returnFalse
orTrue
, respectively.
Instance methods:
- date.replace(year, month, day)¶
Return a date with the same value, except for those parameters given new values by whichever keyword arguments are specified. For example, if
d == date(2002, 12, 30)
, thend.replace(day=26) == date(2002, 12, 26)
.
- date.timetuple()¶
Return a
time.struct_time
such as returned bytime.localtime()
. The hours, minutes and seconds are 0, and the DST flag is -1.d.timetuple()
is equivalent totime.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1))
, whereyday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1
is the day number within the current year starting with1
for Baishak 1st.
- date.weekday()¶
Return the day of the week as an integer, where Sunday is 0 and Saturday is 6. For example,
date(2002, 12, 4).weekday() == 0
, a Sunday.
- date.to_datetime_date()¶
Return the converted
datetime.date
(A.D) object of thenepali_datetime.date
object.Example:
>>> import nepali_datetime >>> ndt = nepali_datetime.date(2075, 7, 21) >>> ndt.to_datetime_date() datetime.date(2018, 11, 7)
- date.isoformat()¶
Return a string representing the date in ISO 8601 format, ‘YYYY-MM-DD’. For example,
date(2002, 12, 4).isoformat() == '2002-12-04'
.
- date.__str__()¶
For a date d,
str(d)
is equivalent tod.isoformat()
.
- date.calendar(justify=4)¶
Dispaly a B.S calendar for the date object’s month with the object’s day highlighted. Override default
justify=4
for wider view of calendar.Example:
>>> import nepali_datetime >>> ndt = nepali_datetime.date(2051, 10, 1) >>> ndt.calendar() Magh 2051 Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
- date.ctime()¶
Return a string representing the date, for example
date(2002, 12, 4).ctime() == 'Wed Cha 4 00:00:00 2002'
.d.ctime()
is equivalent totime.ctime(time.mktime(d.timetuple()))
on platforms where the native Cctime()
function (whichtime.ctime()
invokes, but whichdate.ctime()
does not invoke) conforms to the C standard.
- date.strftime(format)¶
Return a string representing the date, controlled by an explicit format string. Format codes referring to hours, minutes or seconds will see 0 values. For a complete list of formatting directives, see strftime() and strptime() Behavior.
- date.__format__(format)¶
Same as
date.strftime()
. This makes it possible to specify a format string for adate
object when usingstr.format()
. For a complete list of formatting directives, see strftime() and strptime() Behavior.
Example of counting days to an event:
>>> import time
>>> import nepali_datetime
>>> today = nepali_datetime.date.today()
>>> today
nepali_datetime.date(2050, 12, 5)
>>> today == nepali_datetime.date.fromtimestamp(time.time())
True
>>> my_birthday = nepali_datetime.date(today.year, 10, 1)
>>> if my_birthday < today:
... my_birthday = my_birthday.replace(year=today.year + 1)
>>> my_birthday
nepali_datetime.date(2051, 10, 1)
>>> time_to_birthday = abs(my_birthday - today)
>>> time_to_birthday.days
303
Example of working with date
:
>>> import nepali_datetime
>>> d = nepali_datetime.date.fromordinal(10000) # 10000th day after 1. 1. 1975
>>> d
nepali_datetime.date(2002, 5, 12)
>>> d.isoformat()
'2002-05-12'
>>> d.strftime("%d/%m/%y")
'12/05/02'
>>> d.strftime("%A %d. %B %Y")
'Tuesday 12. Bhadau 2002'
>>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month")
'The day is 12, the month is Bhadau.'
nepali_datetime.datetime
Objects¶
A datetime
object is a single object containing all the information
from a date
object and a time
object. Like a date
object, datetime
assumes the current Gregorian calendar extended in
both directions; like a time object, datetime
assumes there are exactly
3600*24 seconds in every day.
Constructor:
- class nepali_datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)¶
The year, month and day arguments are required. tzinfo may be
None
, or an instance of aUTC0545
. The remaining arguments may be integers, in the following ranges:MINYEAR <= year <= MAXYEAR
1 <= month <= 12
1 <= day <= number of days in the given month and year
0 <= hour < 24
0 <= minute < 60
0 <= second < 60
0 <= microsecond < 1000000
If an argument outside those ranges is given,
ValueError
is raised.
Other constructors, all class methods:
- classmethod datetime.now()¶
Return the current local date and time. If optional argument tz is
None
or not specified, this is liketoday()
, but, if possible, supplies more precision than can be gotten from going through atime.time()
timestamp (for example, this may be possible on platforms supplying the Cgettimeofday()
function).The tz is explicitly set to restrict to Nepal timezone which is an instance of
UTC0545
. See alsotoday()
,utcnow()
.
- classmethod datetime.utcnow()¶
Return the current UTC date and time, with
tzinfo
None
. This is likenow()
, but returns the current UTC date and time, as a naivedatetime
object. See alsonow()
.
- classmethod datetime.strptime(date_string, format)¶
Return a
datetime
corresponding to date_string, parsed according to format. This is equivalent todatetime(*(time.strptime(date_string, format)[0:6]))
.ValueError
is raised if the date_string and format can’t be parsed bytime.strptime()
or if it returns a value which isn’t a time tuple. For a complete list of formatting directives, see strftime() and strptime() Behavior.
Class attributes:
- datetime.max¶
The latest representable
datetime
,datetime(MAXYEAR, 12, MAXYEAR_LAST_MONTHS_LAST_DAY, 23, 59, 59, 999999, tzinfo=None)
.
- datetime.resolution¶
The smallest possible difference between non-equal
datetime
objects,timedelta(microseconds=1)
.
Instance attributes (read-only):
- datetime.month¶
Between 1 and 12 inclusive.
- datetime.day¶
Between 1 and the number of days in the given month of the given year.
- datetime.hour¶
In
range(24)
.
- datetime.minute¶
In
range(60)
.
- datetime.second¶
In
range(60)
.
- datetime.microsecond¶
In
range(1000000)
.
- datetime.tzinfo¶
The object passed as the tzinfo argument to the
datetime
constructor, orNone
if none was passed.
Supported operations:
Operation |
Result |
---|---|
|
(1) |
|
(2) |
|
(3) |
|
datetime2 is a duration of timedelta removed from datetime1, moving forward in time if
timedelta.days
> 0, or backward iftimedelta.days
< 0. The result has the sametzinfo
attribute as the input datetime, and datetime2 - datetime1 == timedelta after.OverflowError
is raised if datetime2.year would be smaller thanMINYEAR
or larger thanMAXYEAR
. Note that no time zone adjustments are done even if the input is an aware object.Computes the datetime2 such that datetime2 + timedelta == datetime1. As for addition, the result has the same
tzinfo
attribute as the input datetime, and no time zone adjustments are done even if the input is aware. This isn’t quite equivalent to datetime1 + (-timedelta), because -timedelta in isolation can overflow in cases where datetime1 - timedelta does not.Subtraction of a
datetime
from adatetime
is defined only if both operands are naive, or if both are aware. If one is aware and the other is naive,TypeError
is raised.If both are naive, or both are aware and have the same
tzinfo
attribute, thetzinfo
attributes are ignored, and the result is atimedelta
object t such thatdatetime2 + t == datetime1
. No time zone adjustments are done in this case.If both are aware and have different
tzinfo
attributes,a-b
acts as if a and b were first converted to naive UTC datetimes first. The result is(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) - b.utcoffset())
except that the implementation never overflows.datetime1 is considered less than datetime2 when datetime1 precedes datetime2 in time.
If one comparand is naive and the other is aware,
TypeError
is raised if an order comparison is attempted. For equality comparisons, naive instances are never equal to aware instances.If both comparands are aware, and have the same
tzinfo
attribute, the commontzinfo
attribute is ignored and the base datetimes are compared. If both comparands are aware and have differenttzinfo
attributes, the comparands are first adjusted by subtracting their UTC offsets (obtained fromself.utcoffset()
).
Instance methods:
- datetime.time()¶
Return
time
object with same hour, minute, second and microsecond.tzinfo
isNone
. See also methodtimetz()
.
- datetime.timetz()¶
Return
time
object with same hour, minute, second, microsecond, and tzinfo attributes. See also methodtime()
.
- datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])¶
Return a datetime with the same attributes, except for those attributes given new values by whichever keyword arguments are specified. Note that
tzinfo=None
can be specified to create a naive datetime from an aware datetime with no conversion of date and time data.
- datetime.tzname()¶
If
tzinfo
isNone
, returnsNone
, else returnsself.tzinfo.tzname(self)
, raises an exception if the latter doesn’t returnNone
or a string object,
- datetime.timetuple()¶
Return a
time.struct_time
such as returned bytime.localtime()
.d.timetuple()
is equivalent totime.struct_time((d.year, d.month, d.day, d.hour, d.minute, d.second, d.weekday(), yday, dst))
, whereyday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1
is the day number within the current year starting with1
for Baishak 1st. Thetm_isdst
flag of the result is set according to thedst()
method:tzinfo
isNone
ordst()
returnsNone
,tm_isdst
is set to-1
; else ifdst()
returns a non-zero value,tm_isdst
is set to1
; elsetm_isdst
is set to0
.
- datetime.weekday()¶
Return the day of the week as an integer, where Sunday is 0 and Saturday is 6. The same as
self.date().weekday()
. See alsoisoweekday()
.
- datetime.isoformat(sep='T')¶
- datetime.strftime(format)¶
Return a string representing the date and time, controlled by an explicit format string. For a complete list of formatting directives, see strftime() and strptime() Behavior.
- datetime.__format__(format)¶
Same as
datetime.strftime()
. This makes it possible to specify a format string for adatetime
object when usingstr.format()
. For a complete list of formatting directives, see strftime() and strptime() Behavior.
Examples of working with datetime objects:
>>> import nepali_datetime
>>> # Using datetime.combine()
>>> d = nepali_datetime.date(2005, 7, 14)
>>> t = time(12, 30)
>>> nepali_datetime.datetime.combine(d, t)
nepali_datetime.datetime(2005, 7, 14, 12, 30)
>>> # Using nepali_datetime.datetime.now() or nepali_datetime.datetime.utcnow()
>>> nepali_datetime.datetime.now()
nepali_datetime.datetime(2007, 12, 6, 16, 30, 43, 79043) # GMT +5:45
>>> nepali_datetime.datetime.utcnow()
nepali_datetime.datetime(2007, 12, 6, 10, 45, 43, 79060)
>>> # Using nepali_datetime.datetime.strptime()
>>> dt = nepali_datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
>>> dt
nepali_datetime.datetime(2006, 11, 21, 16, 30)
>>> # Formatting datetime
>>> dt.strftime("%A, %d. %B %Y %I:%M%p")
'Saturday, 21. Falgun 2006 04:30PM'
>>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time")
'The day is 21, the month is Falgun, the time is 04:30PM.'
strftime()
and strptime()
Behavior¶
date
, datetime
, and time
objects all support a
strftime(format)
method, to create a string representing the time under the
control of an explicit format string. Broadly speaking, d.strftime(fmt)
acts like the time
module’s time.strftime(fmt, d.timetuple())
although not all objects support a timetuple()
method.
Conversely, the datetime.strptime()
class method creates a
datetime
object from a string representing a date and time and a
corresponding format string. datetime.strptime(date_string, format)
is
equivalent to datetime(*(time.strptime(date_string, format)[0:6]))
.
For time
objects, the format codes for year, month, and day should not
be used, as time objects have no such values. If they’re used anyway, 1975
is substituted for the year, and 1
for the month and day.
For date
objects, the format codes for hours, minutes, seconds, and
microseconds should not be used, as date
objects have no such
values. If they’re used anyway, 0
is substituted for them.
The following is a list of all the format codes that the C standard (1989 version) requires, and these work on all platforms with a standard C implementation. Note that the 1999 version of the C standard added additional format codes.
Directives |
Meaning |
Example |
Notes |
---|---|---|---|
|
Weekday as locale’s abbreviated name. |
Sun, Mon, …, Sat |
(1) |
|
Weekday as locale’s full name. |
Sunday, Monday, …, Saturday |
(1) |
|
Weekday as locale’s full name in Nepali unicode. |
आइतबार, सोमबार, …, शनिबार |
(1) |
|
Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. |
0, 1, …, 6 |
|
|
Day of the month as a zero-padded decimal number. |
01, 02, …, 32 |
|
|
Day of the month as a zero-padded decimal number in Nepali unicode. |
०१, ०२, …, ३२ |
|
|
Month as locale’s abbreviated name. |
Bai, Jes, …, Cha |
(1) |
|
Month as locale’s full name. |
Baishakh, Jestha, …, Chaitra |
(1) |
|
Month as locale’s full name in Nepali unicode. |
वैशाख, जेष्ठ, असार, श्रावण, भदौ, आश्विन, कार्तिक, मंसिर, पौष, माघ, फाल्गुण, चैत्र |
(1) |
|
Month as a zero-padded decimal number. |
01, 02, …, 12 |
|
|
Month as a zero-padded decimal number. |
०१, ०२,…, १२ |
|
|
Year without century as a zero-padded decimal number. |
00, 01, …, 99 |
(7) |
|
Year without century as a zero-padded decimal number in Nepali unicode. |
००, ०१, …, ९९ |
|
|
Year with century as a decimal number. |
1975, 1976, …, 2077, 2078, …, 2099, 2100 |
(2) |
|
Year with century as a decimal number in Nepali unicode. |
१९७५, १९७६, …, २०९९, २१०० |
(2) |
|
Hour (24-hour clock) as a zero-padded decimal number. |
00, 01, …, 23 |
|
|
Hour (24-hour clock) as a zero-padded decimal number in Nepali unicode. |
००, ०१, …, २३ |
|
|
Hour (12-hour clock) as a zero-padded decimal number. |
01, 02, …, 12 |
|
|
Hour (12-hour clock) as a zero-padded decimal number in Nepali unicode. |
०१, ०२, …, १२ |
|
|
Locale’s equivalent of either AM or PM. |
AM, PM |
(1) |
|
Minute as a zero-padded decimal number. |
00, 01, …, 59 |
|
|
Minute as a zero-padded decimal number in Nepali unicode. |
००, ०१, …, ५९ |
|
|
Second as a zero-padded decimal number. |
00, 01, …, 59 |
(4) |
|
Second as a zero-padded decimal number in Nepali unicode. |
००, ०१, …, ५९ |
(4) |
|
Microsecond as a decimal number, zero-padded on the left. |
000000, 000001, …, 999999 |
(5) |
|
UTC offset in the form +HHMM or -HHMM (empty string if the object is naive). |
(empty), +0000, -0400, +1030 |
(6) |
|
Time zone name (empty string if the object is naive). |
(empty), UTC, EST, CST |
|
|
Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. |
00, 01, …, 53 |
(7) |
Notes:
Because the format depends on the directive
%b
or%B
or%N
, care should be taken when making assumptions about the output value. Field orderings will vary (for example, “month/day/year” versus “day/month/year”), and the output may contain Unicode characters.The
strptime()
method can parse years in the full [1, 9999] range, but years < 1000 must be zero-filled to 4-digit width.When used with the
strptime()
method, the%p
directive only affects the output hour field if the%I
directive is used to parse the hour.Unlike the
time
module, thedatetime
module does not support leap seconds.When used with the
strptime()
method, the%f
directive accepts from one to six digits and zero pads on the right.%f
is an extension to the set of format characters in the C standard (but implemented separately in datetime objects, and therefore always available).For a naive object, the
%z
and%Z
format codes are replaced by empty strings.For an aware object:
%z
utcoffset()
is transformed into a 5-character string of the form +HHMM or -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and MM is a 2-digit string giving the number of UTC offset minutes. For example, ifutcoffset()
returnstimedelta(hours=-3, minutes=-30)
,%z
is replaced with the string'-0330'
.%Z
If
tzname()
returnsNone
,%Z
is replaced by an empty string. Otherwise%Z
is replaced by the returned value, which must be a string.When the
%z
directive is provided to thestrptime()
method, an awaredatetime
object will be produced. Thetzinfo
of the result will be set to atimezone
instance.
The year within century. When a century is not otherwise specified, values in the range [90,99] shall refer to years 1990 to 1999 inclusive, and values in the range [00,89] shall refer to years 2000 to 2089 inclusive; leading zeros shall be permitted but shall not be required.