API reference

sambat

class sambat.date(year, month, day)

Bases: object

A Bikram Sambat (BS) calendar date.

sambat.date mirrors datetime.date: same constructors, methods, operators and error types, with year, month and day in the BS calendar. toordinal() returns the same day number as the standard library, so weekday(), arithmetic and conversion agree exactly with the Gregorian equivalent.

Parameters:
  • year (SupportsIndex) – BS year in MINYEAR..MAXYEAR.

  • month (SupportsIndex) – BS month, 1 (Baishakh) to 12 (Chaitra).

  • day (SupportsIndex) – Day of the month, 1 to the month’s length (up to 32).

Raises:
  • TypeError – If an argument is not an integer.

  • ValueError – If the date does not exist or is outside the supported range.

Return type:

Self

Examples

>>> from sambat import date
>>> d = date(2083, 6, 15)
>>> d.to_gregorian()
datetime.date(2026, 10, 1)
>>> d.strftime("%A, %d %B %Y")
'Thursday, 15 Ashwin 2083'
>>> date.from_gregorian(__import__("datetime").date(2026, 4, 14))
sambat.date(2083, 1, 1)
ctime()[source]

Return a time.ctime()-style string, e.g. 'Thu Ash 15 00:00:00 2083'.

Return type:

str

property day: int

Day of the month (1..32).

days_in_month()[source]

Return the number of days (29..32) in this date’s BS month.

Return type:

int

days_in_year()[source]

Return the number of days (365 or 366) in this date’s BS year.

Return type:

int

classmethod from_gregorian(value, /)[source]

Convert a Gregorian datetime.date to a BS date.

A datetime.datetime is accepted and its date part is used.

Parameters:

value (date) – The Gregorian date.

Returns:

The BS date for the same day.

Raises:
  • TypeError – If value is not a datetime.date.

  • ValueError – If the date is outside the supported range.

Return type:

Self

classmethod fromisocalendar(year, week, day)[source]

Return the date for a BS week-numbering year, week and weekday.

Parameters:
  • year (int) – The BS week-numbering year.

  • week (int) – The week number (1..53).

  • day (int) – The ISO weekday (1 = Monday .. 7 = Sunday).

Returns:

The BS date.

Raises:

ValueError – If the combination is invalid or out of range.

Return type:

Self

classmethod fromisoformat(date_string, /)[source]

Parse a BS date in any ISO 8601 format accepted by Python 3.11+.

Accepted forms are YYYY-MM-DD, YYYYMMDD, YYYY-Www, YYYY-Www-D, YYYYWww and YYYYWwwD (week dates use the BS week calendar of isocalendar()).

Parameters:

date_string (str) – The string to parse.

Returns:

The BS date.

Raises:
  • TypeError – If date_string is not a string.

  • ValueError – If the string is malformed or the date is invalid.

Return type:

Self

classmethod fromordinal(n, /)[source]

Return the date for a proleptic Gregorian ordinal.

Parameters:

n (int) – A day number as returned by toordinal().

Returns:

The BS date.

Raises:

ValueError – If the ordinal is outside the supported range.

Return type:

Self

classmethod fromtimestamp(timestamp, /)[source]

Return the local date corresponding to a POSIX timestamp.

Parameters:

timestamp (float) – Seconds since the epoch, as returned by time.time().

Returns:

The BS date in the machine’s local time zone.

Return type:

Self

isocalendar()[source]

Return the BS week calendar (year, week, weekday).

Weeks run Monday to Sunday and week 1 is the week that contains the first Thursday of the BS year (the ISO 8601 rule applied to BS years). For the Gregorian ISO week use to_gregorian().isocalendar().

Returns:

An IsoCalendarDate named tuple.

Return type:

tuple[int, int, int]

isoformat()[source]

Return the date as YYYY-MM-DD.

Return type:

str

isoweekday()[source]

Return the day of the week, Monday == 1 … Sunday == 7.

Return type:

int

property month: int

BS month (1 = Baishakh .. 12 = Chaitra).

replace(year=None, month=None, day=None)[source]

Return a date with the given fields replaced.

Parameters:
  • year (SupportsIndex | None) – New BS year.

  • month (SupportsIndex | None) – New BS month.

  • day (SupportsIndex | None) – New day of the month.

Returns:

A new instance of the same class.

Return type:

Self

strftime(format, /, *, locale=Locale(name='en', month_names=('Baishakh', 'Jestha', 'Asar', 'Shrawan', 'Bhadra', 'Ashwin', 'Kartik', 'Mangsir', 'Poush', 'Magh', 'Falgun', 'Chaitra'), month_abbrs=('Bai', 'Jes', 'Asa', 'Shr', 'Bha', 'Ash', 'Kar', 'Man', 'Pou', 'Mag', 'Fal', 'Cha'), weekday_names=('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'), weekday_abbrs=('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'), am_pm=('AM', 'PM'), digits='0123456789', datetime_format='%a %b %e %H:%M:%S %Y', date_format='%m/%d/%y', time_format='%H:%M:%S', month_aliases=(('Baisakh', 'Baishak', 'Baisak', 'Vaishakh', 'Vaisakh', 'Vaishakha'), ('Jeth', 'Jyeshtha', 'Jyestha', 'Jestha', 'Jaistha', 'Jesth'), ('Ashadh', 'Asadh', 'Ashar', 'Aashadh', 'Ashad', 'Asad'), ('Saun', 'Sawan', 'Shravan', 'Srawan', 'Sravan'), ('Bhadau', 'Bhado', 'Bhadrapad', 'Bhadra'), ('Asoj', 'Ashoj', 'Aswin', 'Ashvin', 'Asvin', 'Aswhin'), ('Kattik', 'Kartika', 'Karthik', 'Kartick'), ('Mansir', 'Mangshir', 'Marga', 'Margashirsha', 'Mangshir'), ('Push', 'Paush', 'Pous', 'Pausha', 'Pus'), ('Magha',), ('Phagun', 'Phalgun', 'Fagun', 'Phalguna', 'Falgun'), ('Chait', 'Chaitr', 'Chaita')), weekday_aliases=(('Sombar', 'Sombaar'), ('Tues', 'Mangalbar', 'Mangalbaar'), ('Budhbar', 'Budhabar', 'Budhbaar'), ('Thur', 'Thurs', 'Bihibar', 'Bihibaar'), ('Sukrabar', 'Shukrabar', 'Sukrabaar'), ('Sanibar', 'Shanibar', 'Sanibaar'), ('Aaitabar', 'Aitabar', 'Aaitbar', 'Aitbar'))))[source]

Format the date; see the directive table in the documentation.

Parameters:
  • format (str) – The format string.

  • locale (Locale) – Names, digits and templates to use (default EN).

Returns:

The formatted string.

Raises:

ValueError – If the format contains an unknown directive.

Return type:

str

classmethod strptime(date_string, format, /, *, locale=Locale(name='en', month_names=('Baishakh', 'Jestha', 'Asar', 'Shrawan', 'Bhadra', 'Ashwin', 'Kartik', 'Mangsir', 'Poush', 'Magh', 'Falgun', 'Chaitra'), month_abbrs=('Bai', 'Jes', 'Asa', 'Shr', 'Bha', 'Ash', 'Kar', 'Man', 'Pou', 'Mag', 'Fal', 'Cha'), weekday_names=('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'), weekday_abbrs=('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'), am_pm=('AM', 'PM'), digits='0123456789', datetime_format='%a %b %e %H:%M:%S %Y', date_format='%m/%d/%y', time_format='%H:%M:%S', month_aliases=(('Baisakh', 'Baishak', 'Baisak', 'Vaishakh', 'Vaisakh', 'Vaishakha'), ('Jeth', 'Jyeshtha', 'Jyestha', 'Jestha', 'Jaistha', 'Jesth'), ('Ashadh', 'Asadh', 'Ashar', 'Aashadh', 'Ashad', 'Asad'), ('Saun', 'Sawan', 'Shravan', 'Srawan', 'Sravan'), ('Bhadau', 'Bhado', 'Bhadrapad', 'Bhadra'), ('Asoj', 'Ashoj', 'Aswin', 'Ashvin', 'Asvin', 'Aswhin'), ('Kattik', 'Kartika', 'Karthik', 'Kartick'), ('Mansir', 'Mangshir', 'Marga', 'Margashirsha', 'Mangshir'), ('Push', 'Paush', 'Pous', 'Pausha', 'Pus'), ('Magha',), ('Phagun', 'Phalgun', 'Fagun', 'Phalguna', 'Falgun'), ('Chait', 'Chaitr', 'Chaita')), weekday_aliases=(('Sombar', 'Sombaar'), ('Tues', 'Mangalbar', 'Mangalbaar'), ('Budhbar', 'Budhabar', 'Budhbaar'), ('Thur', 'Thurs', 'Bihibar', 'Bihibaar'), ('Sukrabar', 'Shukrabar', 'Sukrabaar'), ('Sanibar', 'Shanibar', 'Sanibaar'), ('Aaitabar', 'Aitabar', 'Aaitbar', 'Aitbar'))))[source]

Parse a BS date from a string according to format.

Time directives are accepted and ignored, as in datetime.date.strptime().

Parameters:
  • date_string (str) – The string to parse.

  • format (str) – A format using the same directives as strftime().

  • locale (Locale) – The locale whose month and weekday names are accepted.

Returns:

The BS date.

Raises:

ValueError – If the string does not match the format.

Return type:

Self

timetuple()[source]

Return a time.struct_time with BS fields.

tm_yday is the day of the BS year and tm_isdst is -1. Do not pass the result to time.mktime(), which assumes Gregorian fields.

Return type:

struct_time

to_gregorian()[source]

Return the Gregorian datetime.date for the same day.

Return type:

date

classmethod today()[source]

Return the current local date (in the machine’s time zone).

Return type:

Self

toordinal()[source]

Return the proleptic Gregorian ordinal (identical to the stdlib’s).

Return type:

int

weekday()[source]

Return the day of the week, Monday == 0 … Sunday == 6.

Return type:

int

property year: int

BS year (MINYEAR..``MAXYEAR``).

class sambat.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

Bases: date

A Bikram Sambat (BS) date with a time of day and optional time zone.

sambat.datetime mirrors datetime.datetime. Time-zone handling, timestamps, comparisons and hashing are delegated to an equivalent Gregorian datetime.datetime (see to_gregorian()), so any tzinfo implementation (zoneinfo, dateutil, pytz) behaves exactly as it does with the standard library.

Parameters:
  • year (SupportsIndex) – BS year in MINYEAR..MAXYEAR.

  • month (SupportsIndex) – BS month, 1 (Baishakh) to 12 (Chaitra).

  • day (SupportsIndex) – Day of the month, 1 to the month’s length (up to 32).

  • hour (SupportsIndex) – 0..23.

  • minute (SupportsIndex) – 0..59.

  • second (SupportsIndex) – 0..59.

  • microsecond (SupportsIndex) – 0..999999.

  • tzinfo (_dt.tzinfo | None) – None for a naive value, or a datetime.tzinfo.

  • fold (int) – 0 or 1, disambiguating repeated wall times (PEP 495).

Return type:

Self

Examples

>>> from sambat import NEPAL_TZ, datetime
>>> dt = datetime(2083, 6, 15, 9, 30, tzinfo=NEPAL_TZ)
>>> dt.isoformat()
'2083-06-15T09:30:00+05:45'
>>> dt.to_gregorian()
datetime.datetime(2026, 10, 1, 9, 30, tzinfo=sambat.NEPAL_TZ)
astimezone(tz=None)[source]

Return the same instant expressed in time zone tz.

Parameters:

tz (tzinfo | None) – The target time zone; None means the system local zone.

Returns:

An aware datetime of the same class.

Return type:

Self

classmethod combine(date, time, tzinfo=<object object>)[source]

Combine a BS date and a datetime.time.

Parameters:
  • date (date) – A sambat.date (a stdlib datetime.date is rejected).

  • time (time) – The time of day.

  • tzinfo (tzinfo | None) – Overrides time.tzinfo when given.

Returns:

The combined BS datetime.

Raises:

TypeError – If the arguments have the wrong types.

Return type:

Self

ctime()[source]

Return a time.ctime()-style string.

Return type:

str

date()[source]

Return the BS date part as a sambat.date.

Return type:

date

dst()[source]

Return the DST adjustment, or None for naive values.

Return type:

timedelta | None

property fold: int

0 or 1; selects the earlier or later of two repeated wall times (PEP 495).

classmethod from_gregorian(value, /)[source]

Convert a Gregorian datetime.datetime to a BS datetime.

A plain datetime.date is accepted and treated as midnight.

Parameters:

value (date) – The Gregorian value; tzinfo and fold are preserved.

Returns:

The BS datetime for the same wall time.

Raises:
  • TypeError – If value is not a datetime.date.

  • ValueError – If the date is outside the supported range.

Return type:

Self

classmethod fromisoformat(date_string, /)[source]

Parse a BS datetime in any ISO 8601 format accepted by Python 3.11+.

The date part uses the BS calendar; the separator may be any single character; the time part accepts everything datetime.time.fromisoformat accepts (including Z and fractional offsets).

Parameters:

date_string (str) – The string to parse.

Returns:

The BS datetime.

Raises:
  • TypeError – If date_string is not a string.

  • ValueError – If the string is malformed or the date is invalid.

Return type:

Self

classmethod fromtimestamp(timestamp, tz=None)[source]

Return the datetime corresponding to a POSIX timestamp.

Parameters:
  • timestamp (float) – Seconds since the epoch.

  • tz (tzinfo | None) – A time zone; when None the result is naive local time.

Returns:

The BS datetime.

Return type:

Self

property hour: int

Hour (0..23).

isoformat(sep='T', timespec='auto')[source]

Return YYYY-MM-DD[sep]HH:MM:SS[.ffffff][+HH:MM].

Parameters:
  • sep (str) – A single character placed between date and time.

  • timespec (str) – auto, hours, minutes, seconds, milliseconds or microseconds.

Returns:

The ISO 8601 string with the BS date.

Return type:

str

property microsecond: int

Microsecond (0..999999).

property minute: int

Minute (0..59).

classmethod now(tz=None)[source]

Return the current date and time.

Parameters:

tz (tzinfo | None) – A time zone; when None the result is naive local time.

Returns:

The current BS datetime.

Return type:

Self

replace(year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, tzinfo=<object object>, *, fold=None)[source]

Return a datetime with the given fields replaced.

Pass tzinfo=None to make an aware value naive.

Returns:

A new instance of the same class.

Parameters:
  • year (SupportsIndex | None)

  • month (SupportsIndex | None)

  • day (SupportsIndex | None)

  • hour (SupportsIndex | None)

  • minute (SupportsIndex | None)

  • second (SupportsIndex | None)

  • microsecond (SupportsIndex | None)

  • tzinfo (tzinfo | None)

  • fold (int | None)

Return type:

Self

property second: int

Second (0..59).

strftime(format, /, *, locale=Locale(name='en', month_names=('Baishakh', 'Jestha', 'Asar', 'Shrawan', 'Bhadra', 'Ashwin', 'Kartik', 'Mangsir', 'Poush', 'Magh', 'Falgun', 'Chaitra'), month_abbrs=('Bai', 'Jes', 'Asa', 'Shr', 'Bha', 'Ash', 'Kar', 'Man', 'Pou', 'Mag', 'Fal', 'Cha'), weekday_names=('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'), weekday_abbrs=('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'), am_pm=('AM', 'PM'), digits='0123456789', datetime_format='%a %b %e %H:%M:%S %Y', date_format='%m/%d/%y', time_format='%H:%M:%S', month_aliases=(('Baisakh', 'Baishak', 'Baisak', 'Vaishakh', 'Vaisakh', 'Vaishakha'), ('Jeth', 'Jyeshtha', 'Jyestha', 'Jestha', 'Jaistha', 'Jesth'), ('Ashadh', 'Asadh', 'Ashar', 'Aashadh', 'Ashad', 'Asad'), ('Saun', 'Sawan', 'Shravan', 'Srawan', 'Sravan'), ('Bhadau', 'Bhado', 'Bhadrapad', 'Bhadra'), ('Asoj', 'Ashoj', 'Aswin', 'Ashvin', 'Asvin', 'Aswhin'), ('Kattik', 'Kartika', 'Karthik', 'Kartick'), ('Mansir', 'Mangshir', 'Marga', 'Margashirsha', 'Mangshir'), ('Push', 'Paush', 'Pous', 'Pausha', 'Pus'), ('Magha',), ('Phagun', 'Phalgun', 'Fagun', 'Phalguna', 'Falgun'), ('Chait', 'Chaitr', 'Chaita')), weekday_aliases=(('Sombar', 'Sombaar'), ('Tues', 'Mangalbar', 'Mangalbaar'), ('Budhbar', 'Budhabar', 'Budhbaar'), ('Thur', 'Thurs', 'Bihibar', 'Bihibaar'), ('Sukrabar', 'Shukrabar', 'Sukrabaar'), ('Sanibar', 'Shanibar', 'Sanibaar'), ('Aaitabar', 'Aitabar', 'Aaitbar', 'Aitbar'))))[source]

Format the datetime; see the directive table in the documentation.

Parameters:
  • format (str)

  • locale (Locale)

Return type:

str

classmethod strptime(date_string, format, /, *, locale=Locale(name='en', month_names=('Baishakh', 'Jestha', 'Asar', 'Shrawan', 'Bhadra', 'Ashwin', 'Kartik', 'Mangsir', 'Poush', 'Magh', 'Falgun', 'Chaitra'), month_abbrs=('Bai', 'Jes', 'Asa', 'Shr', 'Bha', 'Ash', 'Kar', 'Man', 'Pou', 'Mag', 'Fal', 'Cha'), weekday_names=('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'), weekday_abbrs=('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'), am_pm=('AM', 'PM'), digits='0123456789', datetime_format='%a %b %e %H:%M:%S %Y', date_format='%m/%d/%y', time_format='%H:%M:%S', month_aliases=(('Baisakh', 'Baishak', 'Baisak', 'Vaishakh', 'Vaisakh', 'Vaishakha'), ('Jeth', 'Jyeshtha', 'Jyestha', 'Jestha', 'Jaistha', 'Jesth'), ('Ashadh', 'Asadh', 'Ashar', 'Aashadh', 'Ashad', 'Asad'), ('Saun', 'Sawan', 'Shravan', 'Srawan', 'Sravan'), ('Bhadau', 'Bhado', 'Bhadrapad', 'Bhadra'), ('Asoj', 'Ashoj', 'Aswin', 'Ashvin', 'Asvin', 'Aswhin'), ('Kattik', 'Kartika', 'Karthik', 'Kartick'), ('Mansir', 'Mangshir', 'Marga', 'Margashirsha', 'Mangshir'), ('Push', 'Paush', 'Pous', 'Pausha', 'Pus'), ('Magha',), ('Phagun', 'Phalgun', 'Fagun', 'Phalguna', 'Falgun'), ('Chait', 'Chaitr', 'Chaita')), weekday_aliases=(('Sombar', 'Sombaar'), ('Tues', 'Mangalbar', 'Mangalbaar'), ('Budhbar', 'Budhabar', 'Budhbaar'), ('Thur', 'Thurs', 'Bihibar', 'Bihibaar'), ('Sukrabar', 'Shukrabar', 'Sukrabaar'), ('Sanibar', 'Shanibar', 'Sanibaar'), ('Aaitabar', 'Aitabar', 'Aaitbar', 'Aitbar'))))[source]

Parse a BS datetime from a string according to format.

Parameters:
  • date_string (str) – The string to parse.

  • format (str) – A format using the same directives as strftime().

  • locale (Locale) – The locale whose month and weekday names are accepted.

Returns:

The BS datetime; aware when the format contains %z.

Raises:

ValueError – If the string does not match the format.

Return type:

Self

time()[source]

Return the time part (without tzinfo).

Return type:

time

timestamp()[source]

Return the POSIX timestamp (naive values are taken as local time).

Return type:

float

timetuple()[source]

Return a time.struct_time with BS date fields.

Return type:

struct_time

timetz()[source]

Return the time part including tzinfo.

Return type:

time

to_gregorian()[source]

Return the Gregorian datetime.datetime for the same wall time.

Return type:

datetime

classmethod today()[source]

Return the current local date and time (naive).

Return type:

Self

property tzinfo: tzinfo | None

The time zone, or None for naive values.

tzname()[source]

Return the time zone name, or None for naive values.

Return type:

str | None

classmethod utcfromtimestamp(timestamp)[source]

Return the naive UTC datetime for a POSIX timestamp (deprecated, as in Python 3.12).

Use datetime.fromtimestamp(timestamp, tz=UTC) instead.

Parameters:

timestamp (float)

Return type:

Self

classmethod utcnow()[source]

Return the current naive UTC datetime (deprecated, as in Python 3.12).

Use datetime.now(tz=UTC) instead.

Return type:

Self

utcoffset()[source]

Return the UTC offset, or None for naive values.

Return type:

timedelta | None

utctimetuple()[source]

Return a time.struct_time in UTC with BS date fields.

Return type:

struct_time

class sambat.NepalTimeZone

Bases: tzinfo

tzinfo for Nepal (IANA Asia/Kathmandu), including historical offsets.

The single instance is available as sambat.NEPAL_TZ. It follows PEP 495 for the ambiguous and missing wall times created by the 1920 and 1986 offset changes.

Examples

>>> import datetime
>>> from sambat import NEPAL_TZ
>>> datetime.datetime(2026, 10, 1, 12, tzinfo=NEPAL_TZ).utcoffset()
datetime.timedelta(seconds=20700)
>>> datetime.datetime(1980, 1, 1, tzinfo=NEPAL_TZ).tzname()
'+0530'
dst(dt)[source]

Return the daylight saving adjustment, which is always zero.

Parameters:

dt (datetime | None) – A wall time, or None.

Returns:

timedelta(0), or None when dt is None.

Return type:

timedelta | None

fromutc(dt)[source]

Convert a UTC time (with tzinfo set to this object) to local time.

Parameters:

dt (datetime) – A datetime whose fields are UTC and whose tzinfo is self.

Returns:

The local wall time, with fold set for the repeated 1919 minutes.

Raises:
  • TypeError – If dt is not a datetime.

  • ValueError – If dt.tzinfo is not this object.

Return type:

datetime

tzname(dt)[source]

Return the tz database abbreviation for the offset in force.

Parameters:

dt (datetime | None) – A wall time, or None.

Returns:

"LMT", "+0530" or "+0545", or None when dt is None.

Return type:

str | None

utcoffset(dt)[source]

Return the UTC offset in force at local wall time dt.

Parameters:

dt (datetime | None) – A wall time whose tzinfo is this object, or None.

Returns:

The offset, or None when dt is None.

Return type:

timedelta | None

sambat.today_np()[source]

Return today’s BS date in Nepal, whatever the machine’s time zone.

Returns:

The current date in Asia/Kathmandu.

Return type:

date

sambat.now_np()[source]

Return the current aware BS datetime in Nepal time (Asia/Kathmandu).

Returns:

The current datetime with tzinfo=NEPAL_TZ.

Return type:

datetime

sambat.MINYEAR = first BS year in the calendar table

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral. >>> int(‘0b100’, base=0) 4

sambat.MAXYEAR = last BS year in the calendar table

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral. >>> int(‘0b100’, base=0) 4

class sambat.IsoCalendarDate

The named tuple (year, week, weekday) returned by sambat.date.isocalendar() (the standard library’s own type).

sambat.NEPAL_TZ

The Asia/Kathmandu time zone; see sambat.NepalTimeZone.

sambat.timedelta
sambat.time
sambat.timezone
sambat.tzinfo
sambat.UTC

The standard library’s own objects (sambat.timedelta is datetime.timedelta).

sambat.calendar

Bikram Sambat counterpart of the standard library calendar module.

The functions and classes mirror calendar (monthrange, monthcalendar, Calendar, TextCalendar, HTMLCalendar, …) with months in the BS calendar. Weeks start on Monday by default, as in the standard library; pass firstweekday=SUNDAY for the Nepali convention.

DualTextCalendar and DualHTMLCalendar render a month the way printed Nepali wall calendars do: each BS day shows the Gregorian day number beside it.

Examples

>>> from sambat import calendar
>>> calendar.monthrange(2083, 6)  # (weekday of day 1, number of days)
(3, 31)
>>> calendar.isleap(2081), calendar.days_in_year(2081)
(True, 366)
class sambat.calendar.Calendar(firstweekday=0)[source]

Bases: object

Base class producing BS month and year layouts.

Parameters:

firstweekday (int) – The weekday that starts each week (0 = Monday .. 6 = Sunday).

property firstweekday: int

The first day of the week (0 = Monday .. 6 = Sunday).

getfirstweekday()[source]

Return the first weekday.

Return type:

int

setfirstweekday(firstweekday)[source]

Set the first weekday.

Parameters:

firstweekday (int)

Return type:

None

iterweekdays()[source]

Yield the seven weekday numbers in display order.

Return type:

Iterator[int]

itermonthdays(year, month)[source]

Yield day numbers for a month layout, with 0 for padding days.

Parameters:
  • year (int)

  • month (int)

Return type:

Iterator[int]

itermonthdays2(year, month)[source]

Yield (day, weekday) pairs, with day 0 for padding days.

Parameters:
  • year (int)

  • month (int)

Return type:

Iterator[tuple[int, int]]

itermonthdays3(year, month)[source]

Yield (year, month, day) triples covering complete weeks.

Parameters:
  • year (int)

  • month (int)

Return type:

Iterator[tuple[int, int, int]]

itermonthdays4(year, month)[source]

Yield (year, month, day, weekday) tuples covering complete weeks.

Parameters:
  • year (int)

  • month (int)

Return type:

Iterator[tuple[int, int, int, int]]

itermonthdates(year, month)[source]

Yield sambat.date objects covering complete weeks.

Parameters:
  • year (int)

  • month (int)

Return type:

Iterator[date]

monthdatescalendar(year, month)[source]

Return the month as a list of weeks of sambat.date.

Parameters:
  • year (int)

  • month (int)

Return type:

list[list[date]]

monthdays2calendar(year, month)[source]

Return the month as a list of weeks of (day, weekday) pairs.

Parameters:
  • year (int)

  • month (int)

Return type:

list[list[tuple[int, int]]]

monthdayscalendar(year, month)[source]

Return the month as a list of weeks of day numbers (0 for padding).

Parameters:
  • year (int)

  • month (int)

Return type:

list[list[int]]

yeardatescalendar(year, width=3)[source]

Return the year as rows of width months of weeks of dates.

Parameters:
  • year (int)

  • width (int)

Return type:

list[list[list[list[date]]]]

yeardays2calendar(year, width=3)[source]

Return the year as rows of width months of (day, weekday) weeks.

Parameters:
  • year (int)

  • width (int)

Return type:

list[list[list[list[tuple[int, int]]]]]

yeardayscalendar(year, width=3)[source]

Return the year as rows of width months of day-number weeks.

Parameters:
  • year (int)

  • width (int)

Return type:

list[list[list[list[int]]]]

class sambat.calendar.Day(*values)[source]

Bases: IntEnum

Days of the week, numbered as date.weekday() (Monday == 0).

class sambat.calendar.DualHTMLCalendar(firstweekday=6, locale=None)[source]

Bases: LocaleHTMLCalendar

HTML calendar showing each BS day with its Gregorian day number.

Each day cell contains the BS day followed by <span class="ad">AD day</span>. Weeks start on Sunday by default.

Parameters:
  • firstweekday (int) – The first weekday (default 6 = Sunday).

  • locale (Locale | None) – The locale for BS names and digits (default English).

formatmonth(theyear, themonth, withyear=True)[source]

Return a month table whose cells include the Gregorian day.

Parameters:
  • theyear (int)

  • themonth (int)

  • withyear (bool)

Return type:

str

class sambat.calendar.DualTextCalendar(firstweekday=6, locale=None)[source]

Bases: LocaleTextCalendar

Text calendar showing each BS day with its Gregorian day number.

Weeks start on Sunday by default, as on printed Nepali calendars.

Parameters:
  • firstweekday (int) – The first weekday (default 6 = Sunday).

  • locale (Locale) – The locale for BS names and digits (default English).

formatmonth(theyear, themonth, w=0, l=0)[source]

Return a month where each cell reads "<BS day> <AD day>".

Parameters:
  • theyear (int)

  • themonth (int)

  • w (int)

  • l (int)

Return type:

str

class sambat.calendar.HTMLCalendar(firstweekday=0)[source]

Bases: Calendar

HTML BS calendars with English names (see LocaleHTMLCalendar).

Parameters:

firstweekday (int)

formatday(day, weekday)[source]

Return one table cell.

Parameters:
  • day (int)

  • weekday (int)

Return type:

str

formatweek(theweek)[source]

Return one table row.

Parameters:

theweek (Sequence[tuple[int, int]])

Return type:

str

formatweekday(day)[source]

Return one header cell.

Parameters:

day (int)

Return type:

str

formatweekheader()[source]

Return the header row.

Return type:

str

formatmonthname(theyear, themonth, withyear=True)[source]

Return the month-name header row.

Parameters:
  • theyear (int)

  • themonth (int)

  • withyear (bool)

Return type:

str

formatmonth(theyear, themonth, withyear=True)[source]

Return a month as an HTML table.

Parameters:
  • theyear (int)

  • themonth (int)

  • withyear (bool)

Return type:

str

formatyear(theyear, width=3)[source]

Return a year as an HTML table with width months per row.

Parameters:
  • theyear (int)

  • width (int)

Return type:

str

formatyearpage(theyear, width=3, css='calendar.css', encoding=None)[source]

Return a complete HTML page for a year, encoded as bytes.

Parameters:
  • theyear (int)

  • width (int)

  • css (str | None)

  • encoding (str | None)

Return type:

bytes

formatmonthpage(theyear, themonth, *, css='calendar.css', encoding=None)[source]

Return a complete HTML page for one month, encoded as bytes.

Parameters:
  • theyear (int)

  • themonth (int)

  • css (str | None)

  • encoding (str | None)

Return type:

bytes

exception sambat.calendar.IllegalMonthError(month)[source]

Bases: ValueError

Raised for a month number outside 1..12.

Parameters:

month (int)

Return type:

None

exception sambat.calendar.IllegalWeekdayError(weekday)[source]

Bases: ValueError

Raised for a weekday number outside 0..6.

Parameters:

weekday (int)

Return type:

None

class sambat.calendar.LocaleHTMLCalendar(firstweekday=0, locale=None)[source]

Bases: HTMLCalendar

An HTMLCalendar using a sambat Locale.

Parameters:
  • firstweekday (int) – The first weekday (0 = Monday .. 6 = Sunday).

  • locale (Locale | None) – The locale to use (default English).

class sambat.calendar.LocaleTextCalendar(firstweekday=0, locale=None)[source]

Bases: TextCalendar

A TextCalendar using a sambat Locale.

Parameters:
  • firstweekday (int) – The first weekday (0 = Monday .. 6 = Sunday).

  • locale (Locale) – The locale to use (default English).

class sambat.calendar.Month(*values)[source]

Bases: IntEnum

The twelve Bikram Sambat months.

class sambat.calendar.TextCalendar(firstweekday=0)[source]

Bases: Calendar

Plain-text BS calendars with English names (see LocaleTextCalendar).

Parameters:

firstweekday (int)

prweek(theweek, width)[source]

Print one week (no trailing newline).

Parameters:
  • theweek (Sequence[tuple[int, int]])

  • width (int)

Return type:

None

formatday(day, weekday, width)[source]

Return a day number centred in width columns (blank for 0).

Parameters:
  • day (int)

  • weekday (int)

  • width (int)

Return type:

str

formatweek(theweek, width)[source]

Return one week as a single line.

Parameters:
  • theweek (Sequence[tuple[int, int]])

  • width (int)

Return type:

str

formatweekday(day, width)[source]

Return a weekday name truncated and centred to width columns.

Parameters:
  • day (int)

  • width (int)

Return type:

str

formatweekheader(width)[source]

Return the weekday header line.

Parameters:

width (int)

Return type:

str

formatmonthname(theyear, themonth, width, withyear=True)[source]

Return the month name (and year) centred in width columns.

Parameters:
  • theyear (int)

  • themonth (int)

  • width (int)

  • withyear (bool)

Return type:

str

prmonth(theyear, themonth, w=0, l=0)[source]

Print a month calendar.

Parameters:
  • theyear (int)

  • themonth (int)

  • w (int)

  • l (int)

Return type:

None

formatmonth(theyear, themonth, w=0, l=0)[source]

Return a month calendar as a multi-line string.

Parameters:
  • theyear (int)

  • themonth (int)

  • w (int)

  • l (int)

Return type:

str

formatyear(theyear, w=2, l=1, c=6, m=3)[source]

Return a whole year as a multi-line string, m months per row.

Parameters:
  • theyear (int)

  • w (int)

  • l (int)

  • c (int)

  • m (int)

Return type:

str

pryear(theyear, w=0, l=0, c=6, m=3)[source]

Print a whole year.

Parameters:
  • theyear (int)

  • w (int)

  • l (int)

  • c (int)

  • m (int)

Return type:

None

sambat.calendar.calendar(theyear, w=2, l=1, c=6, m=3)

Return a whole year as a multi-line string, m months per row.

Parameters:
  • theyear (int)

  • w (int)

  • l (int)

  • c (int)

  • m (int)

Return type:

str

sambat.calendar.day_abbr: tuple[str, ...] = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')

Abbreviated English weekday names, Monday first.

sambat.calendar.day_name: tuple[str, ...] = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')

English weekday names, Monday first.

sambat.calendar.days_in_month(year, month)[source]

Return the number of days (29..32) in a BS month.

Parameters:
  • year (int)

  • month (int)

Return type:

int

sambat.calendar.days_in_year(year)[source]

Return the number of days (365 or 366) in a BS year.

Parameters:

year (int)

Return type:

int

sambat.calendar.error

alias of ValueError

sambat.calendar.firstweekday()

Return the first weekday.

Return type:

int

sambat.calendar.format(cols, colwidth=20, spacing=6)[source]

Print formatstring(cols, colwidth, spacing).

Parameters:
  • cols (Iterable[str])

  • colwidth (int)

  • spacing (int)

Return type:

None

sambat.calendar.formatstring(cols, colwidth=20, spacing=6)[source]

Return cols centred in colwidth columns and joined by spacing spaces.

Parameters:
  • cols (Iterable[str])

  • colwidth (int)

  • spacing (int)

Return type:

str

sambat.calendar.isleap(year)[source]

Return whether the BS year has 366 days.

BS has no leap rule; a year simply has 365 or 366 days.

Parameters:

year (int)

Return type:

bool

sambat.calendar.leapdays(y1, y2)[source]

Return the number of 366-day BS years in range(y1, y2).

Parameters:
  • y1 (int)

  • y2 (int)

Return type:

int

sambat.calendar.main(args=None)[source]

Run the python -m sambat.calendar command line interface.

Parameters:

args (Sequence[str] | None) – Command line arguments (defaults to sys.argv[1:]).

Returns:

The process exit status.

Return type:

int

sambat.calendar.month(theyear, themonth, w=0, l=0)

Return a month calendar as a multi-line string.

Parameters:
  • theyear (int)

  • themonth (int)

  • w (int)

  • l (int)

Return type:

str

sambat.calendar.month_abbr: tuple[str, ...] = ('', 'Bai', 'Jes', 'Asa', 'Shr', 'Bha', 'Ash', 'Kar', 'Man', 'Pou', 'Mag', 'Fal', 'Cha')

Abbreviated English BS month names (index 0 is empty).

sambat.calendar.month_name: tuple[str, ...] = ('', 'Baishakh', 'Jestha', 'Asar', 'Shrawan', 'Bhadra', 'Ashwin', 'Kartik', 'Mangsir', 'Poush', 'Magh', 'Falgun', 'Chaitra')

English BS month names; month_name[1] == 'Baishakh' (index 0 is empty).

sambat.calendar.monthcalendar(year, month)

Return the month as a list of weeks of day numbers (0 for padding).

Parameters:
  • year (int)

  • month (int)

Return type:

list[list[int]]

sambat.calendar.monthrange(year, month)[source]

Return (weekday of the first day, number of days) for a BS month.

Raises:

IllegalMonthError – If month is not in 1..12.

Parameters:
  • year (int)

  • month (int)

Return type:

tuple[int, int]

sambat.calendar.prcal(theyear, w=0, l=0, c=6, m=3)

Print a whole year.

Parameters:
  • theyear (int)

  • w (int)

  • l (int)

  • c (int)

  • m (int)

Return type:

None

sambat.calendar.prmonth(theyear, themonth, w=0, l=0)

Print a month calendar.

Parameters:
  • theyear (int)

  • themonth (int)

  • w (int)

  • l (int)

Return type:

None

sambat.calendar.prweek(theweek, width)

Print one week (no trailing newline).

Parameters:
  • theweek (Sequence[tuple[int, int]])

  • width (int)

Return type:

None

sambat.calendar.setfirstweekday(firstweekday)[source]

Set the first weekday used by the module-level functions.

Raises:

IllegalWeekdayError – If firstweekday is not in 0..6.

Parameters:

firstweekday (int)

Return type:

None

sambat.calendar.standalone_month_abbr: tuple[str, ...] = ('', 'Bai', 'Jes', 'Asa', 'Shr', 'Bha', 'Ash', 'Kar', 'Man', 'Pou', 'Mag', 'Fal', 'Cha')

Abbreviated standalone month names (Python 3.15+); identical to month_abbr.

sambat.calendar.standalone_month_name: tuple[str, ...] = ('', 'Baishakh', 'Jestha', 'Asar', 'Shrawan', 'Bhadra', 'Ashwin', 'Kartik', 'Mangsir', 'Poush', 'Magh', 'Falgun', 'Chaitra')

Month names used on their own (Python 3.15+); identical to month_name for BS.

sambat.calendar.supported_range()[source]

Return (MINYEAR, MAXYEAR), the BS years this version supports.

Return type:

tuple[int, int]

sambat.calendar.timegm(tuple)[source]

Return the POSIX timestamp of a UTC BS (year, month, day, hour, minute, second) tuple.

The inverse of sambat.datetime.utctimetuple() followed by this function.

Parameters:

tuple (Sequence[int])

Return type:

int

sambat.calendar.week(theweek, width)

Return one week as a single line.

Parameters:
  • theweek (Sequence[tuple[int, int]])

  • width (int)

Return type:

str

sambat.calendar.weekday(year, month, day)[source]

Return the weekday (Monday == 0) of a BS date.

Parameters:
  • year (int)

  • month (int)

  • day (int)

Return type:

int

sambat.calendar.weekheader(width)

Return the weekday header line.

Parameters:

width (int)

Return type:

str

sambat.delta

Calendar arithmetic in BS months and years.

timedelta measures exact days. Adding “one month” in the Bikram Sambat calendar needs a rule, because months have 29 to 32 days. relativedelta follows the semantics of dateutil.relativedelta, applied to BS fields: years and months are added first, the day is then clamped to the length of the resulting month, and finally days, weeks and time are added.

Examples

>>> from sambat import date
>>> from sambat.delta import add_months, diff, relativedelta
>>> date(2083, 3, 32) + relativedelta(months=1)  # Asar 32 -> Shrawan has 31 days
sambat.date(2083, 4, 31)
>>> add_months(date(2083, 3, 32), 1, overflow="raise")
Traceback (most recent call last):
    ...
ValueError: day must be in 1..31 for BS 2083-04, not 32
>>> diff(date(2056, 4, 12), date(2083, 6, 15))
relativedelta(years=+27, months=+2, days=+3)
class sambat.delta.Weekday(weekday, n=None)[source]

Bases: object

A weekday, optionally with an occurrence n (FR(+1), MO(-2)).

Used as relativedelta(weekday=FR(+1)): move to the next Friday (or stay on today if it is a Friday).

Parameters:
  • weekday (int) – 0 (Monday) to 6 (Sunday).

  • n (int | None) – Which occurrence; positive looks forward, negative backward.

sambat.delta.add_months(value, months, *, overflow='clamp')[source]

Add months BS months to value.

Parameters:
  • value (_DateT) – A sambat date or datetime.

  • months (int) – The number of months to add (may be negative).

  • overflow (Literal['clamp', 'raise']) – "clamp" (default) or "raise" when the day does not exist in the target month.

Returns:

The shifted value.

Return type:

_DateT

sambat.delta.add_years(value, years, *, overflow='clamp')[source]

Add years BS years to value (same month and day where possible).

Parameters:
  • value (_DateT) – A sambat date or datetime.

  • years (int) – The number of years to add (may be negative).

  • overflow (Literal['clamp', 'raise']) – "clamp" (default) or "raise" when the day does not exist in the target month.

Returns:

The shifted value.

Return type:

_DateT

sambat.delta.diff(start, end)[source]

Return the BS calendar difference from start to end.

start + diff(start, end) == end always holds. Use it for ages: diff(birth_date, today).

Parameters:
  • start (date) – The earlier (or reference) date.

  • end (date) – The later date.

Returns:

A relativedelta with years, months, days (and time fields for datetimes).

Return type:

relativedelta

class sambat.delta.relativedelta(dt1=None, dt2=None, *, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, microseconds=0, year=None, month=None, day=None, weekday=None, hour=None, minute=None, second=None, microsecond=None)[source]

Bases: object

A duration in BS calendar units, with optional absolute fields.

Relative fields (plural: years, months, weeks, days, hours, …) are added; absolute fields (singular: year, month, day, weekday, hour, …) replace the corresponding value.

relativedelta(dt1, dt2) computes the difference dt1 - dt2 such that dt2 + relativedelta(dt1, dt2) == dt1.

Raises:

TypeError – If dt1/dt2 are not sambat dates or a field is not an integer.

Parameters:
  • dt1 (date | None)

  • dt2 (date | None)

  • years (int)

  • months (int)

  • weeks (int)

  • days (int)

  • hours (int)

  • minutes (int)

  • seconds (int)

  • microseconds (int)

  • year (int | None)

  • month (int | None)

  • day (int | None)

  • weekday (Weekday | None)

  • hour (int | None)

  • minute (int | None)

  • second (int | None)

  • microsecond (int | None)

apply(value, *, overflow='clamp')[source]

Add this delta to value, choosing how to handle short months.

Parameters:
  • value (_DateT) – A sambat date or datetime.

  • overflow (Literal['clamp', 'raise']) – "clamp" moves an invalid day to the last day of the month (the + behaviour); "raise" raises ValueError.

Returns:

The shifted value.

Raises:

ValueError – If overflow="raise" and the day does not exist.

Return type:

_DateT

sambat.periods

Month, year and week boundaries, and ranges of BS dates.

Functions that take a datetime keep its time of day and tzinfo; only the date part moves.

Examples

>>> from sambat import date
>>> from sambat.periods import MonthPeriod, date_range, month_end
>>> month_end(date(2083, 3, 10))
sambat.date(2083, 3, 32)
>>> MonthPeriod(2083, 6).days
31
>>> [str(d) for d in date_range(date(2083, 3, 31), date(2083, 4, 2))]
['2083-03-31', '2083-03-32', '2083-04-01']
class sambat.periods.MonthPeriod(year, month)[source]

Bases: Period

One BS month.

Parameters:
  • year (int) – The BS year.

  • month (int) – The BS month (1..12).

Examples

>>> from sambat.periods import MonthPeriod
>>> m = MonthPeriod(2083, 3)
>>> m.start, m.end, m.days
(sambat.date(2083, 3, 1), sambat.date(2083, 3, 32), 32)
>>> m.next()
MonthPeriod(2083, 4)
classmethod of(value)[source]

Return the month containing value.

Parameters:

value (date)

Return type:

Self

next()[source]

Return the following month.

Return type:

MonthPeriod

prev()[source]

Return the preceding month.

Return type:

MonthPeriod

class sambat.periods.Period(start, end)[source]

Bases: object

An inclusive range of BS dates, start to end.

Parameters:
  • start (date) – The first day.

  • end (date) – The last day (must not precede start).

property days: int

The number of days in the period.

dates()[source]

Yield every day of the period.

Return type:

Iterator[date]

class sambat.periods.YearPeriod(year)[source]

Bases: Period

One BS year (Baishakh 1 to the end of Chaitra).

Parameters:

year (int) – The BS year.

classmethod of(value)[source]

Return the year containing value.

Parameters:

value (date)

Return type:

Self

months()[source]

Return the twelve months of the year.

Return type:

list[MonthPeriod]

next()[source]

Return the following year.

Return type:

YearPeriod

prev()[source]

Return the preceding year.

Return type:

YearPeriod

sambat.periods.date_range(start, stop, step=None)[source]

Yield values from start up to, but excluding, stop.

Like range(), the interval is half-open and step may be negative. With a relativedelta step, the n-th value is start + n * step, so month steps do not drift after a short month.

Parameters:
  • start (_DateT) – The first value.

  • stop (_DateT) – The exclusive bound.

  • step (_dt.timedelta | relativedelta | None) – A timedelta or relativedelta (default one day).

Yields:

Successive values of the same type as start.

Raises:

ValueError – If step is zero.

Return type:

Iterator[_DateT]

sambat.periods.month_end(value)[source]

Return the last day of value’s BS month.

Parameters:

value (_DateT)

Return type:

_DateT

sambat.periods.month_start(value)[source]

Return the first day of value’s BS month.

Parameters:

value (_DateT)

Return type:

_DateT

sambat.periods.week_end(value, *, first=Day.SUNDAY)[source]

Return the last day of value’s week (see week_start()).

Parameters:
  • value (_DateT)

  • first (int)

Return type:

_DateT

sambat.periods.week_start(value, *, first=Day.SUNDAY)[source]

Return the first day of value’s week.

Parameters:
  • value (_DateT) – A sambat date or datetime.

  • first (int) – The weekday that starts the week (default Sunday, the Nepali convention; 0 = Monday .. 6 = Sunday).

Returns:

The start of the week.

Return type:

_DateT

sambat.periods.year_end(value)[source]

Return the last day of Chaitra in value’s BS year.

Parameters:

value (_DateT)

Return type:

_DateT

sambat.periods.year_start(value)[source]

Return Baishakh 1 of value’s BS year.

Parameters:

value (_DateT)

Return type:

_DateT

sambat.fiscal

Nepal’s fiscal year and its standard subdivisions.

The Government of Nepal’s fiscal year starts on Shrawan 1 and ends on the last day of Asar of the next BS year, so fiscal year 2083/84 runs from 2083-04-01 to the end of Asar 2084. It is divided into:

  • four quarters (त्रैमासिक) of three months: Shrawan-Asoj, Kartik-Poush, Magh-Chaitra and Baishakh-Asar;

  • three chaumasik (चौमासिक) periods of four months, used for budget reviews: Shrawan-Kartik, Mangsir-Falgun and Chaitra-Asar;

  • two halves (अर्धवार्षिक) of six months: Shrawan-Poush and Magh-Asar.

Organisations whose year starts in another month can pass start_month.

A fiscal year that ends after sambat.MAXYEAR can still be created and queried; only boundaries that fall in unpublished BS years raise ValueError.

Examples

>>> from sambat import date
>>> from sambat.fiscal import FiscalYear
>>> fy = FiscalYear.of(date(2083, 6, 15))
>>> fy.label
'2083/84'
>>> fy.quarter_of(date(2083, 6, 15)), fy.chaumasik_of(date(2083, 6, 15))
(1, 1)
>>> fy.quarter(1)
Period(sambat.date(2083, 4, 1), sambat.date(2083, 6, 31))
sambat.fiscal.SHRAWAN = 4

The month (Shrawan) in which Nepal’s government fiscal year starts.

class sambat.fiscal.FiscalYear(start_year, *, start_month=4)[source]

Bases: object

A fiscal year identified by the BS year in which it starts.

Parameters:
  • start_year (int) – The BS year containing the first day (2083 for 2083/84).

  • start_month (int) – The first month (default 4, Shrawan).

Raises:

ValueError – If start_month is not in 1..12.

classmethod of(value, *, start_month=4)[source]

Return the fiscal year that contains value.

Parameters:
  • value (date) – A sambat date or datetime.

  • start_month (int) – The first month of the fiscal year.

Returns:

The containing fiscal year.

Return type:

Self

classmethod from_label(label, *, start_month=4)[source]

Parse a label such as "2083/84", "2083-2084" or "२०८३/८४".

Parameters:
  • label (str) – The fiscal year label.

  • start_month (int) – The first month of the fiscal year.

Returns:

The fiscal year.

Raises:

ValueError – If the label is malformed or its two years do not follow each other.

Return type:

Self

property label: str

The conventional label, e.g. "2083/84".

property label_ne: str

The label in Devanagari digits, e.g. "२०८३/८४".

property start: date

The first day of the fiscal year.

property end: date

The last day of the fiscal year.

Raises:

ValueError – If that day falls in a BS year not yet in the calendar table.

property days: int

The number of days in the fiscal year.

months()[source]

Return the twelve months of the fiscal year, in order.

Return type:

list[MonthPeriod]

iter_months()[source]

Yield the months of the fiscal year lazily.

Unlike months(), this works for fiscal years that extend past sambat.MAXYEAR until the first unpublished month is reached.

Return type:

Iterator[MonthPeriod]

quarter(number)[source]

Return quarter number (1..4), three months each.

Parameters:

number (int)

Return type:

Period

chaumasik(number)[source]

Return chaumasik period number (1..3), four months each.

Parameters:

number (int)

Return type:

Period

half(number)[source]

Return half number (1..2), six months each.

Parameters:

number (int)

Return type:

Period

fiscal_month(value)[source]

Return the 1-based month of the fiscal year in which value falls.

Raises:

ValueError – If value is not in this fiscal year.

Parameters:

value (date)

Return type:

int

quarter_of(value)[source]

Return the quarter (1..4) containing value.

Parameters:

value (date)

Return type:

int

chaumasik_of(value)[source]

Return the chaumasik period (1..3) containing value.

Parameters:

value (date)

Return type:

int

half_of(value)[source]

Return the half (1..2) containing value.

Parameters:

value (date)

Return type:

int

next()[source]

Return the following fiscal year.

Return type:

FiscalYear

prev()[source]

Return the preceding fiscal year.

Return type:

FiscalYear

sambat.locale

Names, digits and format templates used by strftime and strptime.

A Locale is an immutable bundle of the strings that differ between languages. Two locales are built in:

  • EN - English transliterations with ASCII digits (the default).

  • NE - Nepali in Devanagari script with Devanagari digits.

Locales are always passed explicitly (d.strftime(fmt, locale=NE)); the process-wide C locale is never consulted, so output is identical on every platform and thread-safe.

Examples

>>> import dataclasses
>>> from sambat import date
>>> from sambat.locale import NE
>>> date(2083, 6, 15).strftime("%d %B %Y", locale=NE)
'१५ असोज २०८३'
>>> ne_ascii = dataclasses.replace(NE, digits="0123456789")
>>> date(2083, 6, 15).strftime("%d %B %Y", locale=ne_ascii)
'15 असोज 2083'
sambat.locale.EN = Locale(name='en', month_names=('Baishakh', 'Jestha', 'Asar', 'Shrawan', 'Bhadra', 'Ashwin', 'Kartik', 'Mangsir', 'Poush', 'Magh', 'Falgun', 'Chaitra'), month_abbrs=('Bai', 'Jes', 'Asa', 'Shr', 'Bha', 'Ash', 'Kar', 'Man', 'Pou', 'Mag', 'Fal', 'Cha'), weekday_names=('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'), weekday_abbrs=('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'), am_pm=('AM', 'PM'), digits='0123456789', datetime_format='%a %b %e %H:%M:%S %Y', date_format='%m/%d/%y', time_format='%H:%M:%S', month_aliases=(('Baisakh', 'Baishak', 'Baisak', 'Vaishakh', 'Vaisakh', 'Vaishakha'), ('Jeth', 'Jyeshtha', 'Jyestha', 'Jestha', 'Jaistha', 'Jesth'), ('Ashadh', 'Asadh', 'Ashar', 'Aashadh', 'Ashad', 'Asad'), ('Saun', 'Sawan', 'Shravan', 'Srawan', 'Sravan'), ('Bhadau', 'Bhado', 'Bhadrapad', 'Bhadra'), ('Asoj', 'Ashoj', 'Aswin', 'Ashvin', 'Asvin', 'Aswhin'), ('Kattik', 'Kartika', 'Karthik', 'Kartick'), ('Mansir', 'Mangshir', 'Marga', 'Margashirsha', 'Mangshir'), ('Push', 'Paush', 'Pous', 'Pausha', 'Pus'), ('Magha',), ('Phagun', 'Phalgun', 'Fagun', 'Phalguna', 'Falgun'), ('Chait', 'Chaitr', 'Chaita')), weekday_aliases=(('Sombar', 'Sombaar'), ('Tues', 'Mangalbar', 'Mangalbaar'), ('Budhbar', 'Budhabar', 'Budhbaar'), ('Thur', 'Thurs', 'Bihibar', 'Bihibaar'), ('Sukrabar', 'Shukrabar', 'Sukrabaar'), ('Sanibar', 'Shanibar', 'Sanibaar'), ('Aaitabar', 'Aitabar', 'Aaitbar', 'Aitbar')))

English month and weekday names with ASCII digits.

sambat.locale.NE = Locale(name='ne', month_names=('बैशाख', 'जेठ', 'असार', 'साउन', 'भदौ', 'असोज', 'कात्तिक', 'मंसिर', 'पुस', 'माघ', 'फागुन', 'चैत'), month_abbrs=('बैशाख', 'जेठ', 'असार', 'साउन', 'भदौ', 'असोज', 'कात्तिक', 'मंसिर', 'पुस', 'माघ', 'फागुन', 'चैत'), weekday_names=('सोमबार', 'मङ्गलबार', 'बुधबार', 'बिहीबार', 'शुक्रबार', 'शनिबार', 'आइतबार'), weekday_abbrs=('सोम', 'मङ्गल', 'बुध', 'बिही', 'शुक्र', 'शनि', 'आइत'), am_pm=('पूर्वाह्न', 'अपराह्न'), digits='०१२३४५६७८९', datetime_format='%Y %B %d, %A %H:%M:%S', date_format='%Y/%m/%d', time_format='%H:%M:%S', month_aliases=(('वैशाख', 'बैसाख', 'वैसाख'), ('ज्येष्ठ', 'जेष्ठ', 'जेठ'), ('आषाढ', 'असाढ', 'अषाढ'), ('श्रावण', 'सावन'), ('भाद्र', 'भाद्रपद'), ('आश्विन', 'असोझ'), ('कार्तिक', 'कातिक'), ('मङ्सिर', 'मार्गशीर्ष', 'मङ्गसिर', 'मंगसिर'), ('पौष', 'पूस'), ('माघ',), ('फाल्गुन', 'फाल्गुण'), ('चैत्र',)), weekday_aliases=(('सोमवार',), ('मंगलबार', 'मङ्गलवार', 'मंगलवार', 'मंगल'), ('बुधवार',), ('बिहिबार', 'बिहीवार', 'बृहस्पतिबार', 'बिहि'), ('शुक्रवार',), ('शनिवार',), ('आइतवार', 'आईतबार')))

Nepali (Devanagari) month and weekday names with Devanagari digits.

class sambat.locale.Locale(name, month_names, month_abbrs, weekday_names, weekday_abbrs, am_pm, digits, datetime_format, date_format, time_format, month_aliases=((), (), (), (), (), (), (), (), (), (), (), ()), weekday_aliases=((), (), (), (), (), (), ()))[source]

Bases: object

Language-specific strings for formatting and parsing BS dates.

Weekday sequences start on Monday, matching date.weekday().

Parameters:
  • name (str)

  • month_names (tuple[str, ...])

  • month_abbrs (tuple[str, ...])

  • weekday_names (tuple[str, ...])

  • weekday_abbrs (tuple[str, ...])

  • am_pm (tuple[str, str])

  • digits (str)

  • datetime_format (str)

  • date_format (str)

  • time_format (str)

  • month_aliases (tuple[tuple[str, ...], ...])

  • weekday_aliases (tuple[tuple[str, ...], ...])

name

A short identifier such as "en" or "ne".

Type:

str

month_names

The 12 BS month names, Baishakh first (%B).

Type:

tuple[str, …]

month_abbrs

The 12 abbreviated month names (%b).

Type:

tuple[str, …]

weekday_names

The 7 weekday names, Monday first (%A).

Type:

tuple[str, …]

weekday_abbrs

The 7 abbreviated weekday names (%a).

Type:

tuple[str, …]

am_pm

The ante/post meridiem markers (%p).

Type:

tuple[str, str]

digits

The ten digits used for numeric fields, in value order.

Type:

str

datetime_format

The expansion of %c.

Type:

str

date_format

The expansion of %x.

Type:

str

time_format

The expansion of %X.

Type:

str

month_aliases

Extra spellings accepted when parsing each month.

Type:

tuple[tuple[str, …], …]

weekday_aliases

Extra spellings accepted when parsing each weekday.

Type:

tuple[tuple[str, …], …]

format_number(text)[source]

Render the ASCII digits in text with this locale’s digits.

Parameters:

text (str) – A string that may contain ASCII digits.

Returns:

The string with digits mapped to digits.

Return type:

str

month_spellings(month)[source]

Return every spelling accepted when parsing month (1..12).

Parameters:

month (int) – A month number in 1..12.

Returns:

The full name, abbreviation and aliases, without duplicates.

Return type:

tuple[str, …]

weekday_spellings(weekday)[source]

Return every spelling accepted when parsing weekday (Monday = 0).

Parameters:

weekday (int) – A weekday number in 0..6.

Returns:

The full name, abbreviation and aliases, without duplicates.

Return type:

tuple[str, …]

sambat.locale.get_locale(name)[source]

Return a built-in locale by name.

Parameters:

name (str) – "en" or "ne" (case-insensitive).

Returns:

The matching Locale.

Raises:

LookupError – If no built-in locale has that name.

Return type:

Locale

sambat.text

Conversion between ASCII and Devanagari digits.

Devanagari digits are the Unicode code points U+0966 (०) through U+096F (९). The conversion is exact and leaves every other character untouched.

Examples

>>> from sambat.text import to_ascii_digits, to_nepali_digits
>>> to_nepali_digits("2083-06-15")
'२०८३-०६-१५'
>>> to_ascii_digits("२०८३ असोज १५")
'2083 असोज 15'
sambat.text.ASCII_DIGITS = '0123456789'

The ten ASCII digits, in value order.

sambat.text.DEVANAGARI_DIGITS = '०१२३४५६७८९'

The ten Devanagari digits (U+0966..U+096F), in value order.

sambat.text.to_ascii_digits(text)[source]

Replace every Devanagari digit in text with its ASCII digit.

Parameters:

text (str) – Any string.

Returns:

The string with ०-९ replaced by 0-9.

Return type:

str

sambat.text.to_nepali_digits(text)[source]

Replace every ASCII digit in text with its Devanagari digit.

Parameters:

text (str) – Any string.

Returns:

The string with 0-9 replaced by ०-९.

Return type:

str

sambat.compat

Helpers for migrating from the nepali-datetime package.

The conversion functions are deprecated aliases kept for two minor releases; new code should use sambat.date.from_gregorian() and sambat.date.to_gregorian().

translate_format() rewrites nepali-datetime format strings, whose custom letters (%K, %N, %G, …) collide with standard strftime directives, into sambat’s locale= + %O equivalents.

Examples

>>> from sambat import date
>>> from sambat.compat import translate_format
>>> fmt, locale = translate_format("%K-%n-%D %N")
>>> fmt
'%OY-%Om-%Od %B'
>>> date(2083, 6, 15).strftime(fmt, locale=locale)
'२०८३-०६-१५ असोज'
sambat.compat.from_datetime_date(value)[source]

Deprecated alias of sambat.date.from_gregorian().

Parameters:

value (date)

Return type:

date

sambat.compat.from_datetime_datetime(value)[source]

Deprecated alias of sambat.datetime.from_gregorian().

Parameters:

value (datetime)

Return type:

datetime

sambat.compat.to_datetime_date(value)[source]

Deprecated alias of sambat.date.to_gregorian().

Parameters:

value (date)

Return type:

date

sambat.compat.to_datetime_datetime(value)[source]

Deprecated alias of sambat.datetime.to_gregorian().

Parameters:

value (datetime)

Return type:

datetime

sambat.compat.translate_format(old_format)[source]

Translate a nepali-datetime format string to a sambat one.

Parameters:

old_format (str) – A format string written for nepali-datetime.

Returns:

(new_format, locale) to pass to strftime(new_format, locale=locale). The locale is Nepali (with ASCII digits for plain numeric directives) when the old format used Nepali names, otherwise English.

Raises:

ValueError – If the format uses an unsupported directive, or mixes English and Nepali names (split it into two calls instead).

Return type:

tuple[str, Locale]