Python

Constant dripping wears away a stone

Calendar, Time, and Datetime


Calendar, Time, and Datetime: Python's calendar, time, and datetime modules provide various canlendar, time, and date related functions.

  • calendar Module: The calendar module provides dates, weeks, months, and years related functions. To use the functions, useimport calendarto import the module first.
    • calendar.calendar(year[, width=2, lines=1, space=6]): Returns a string represented calendar for the yearyear. The string is formatted into three columns separated byspacespaces withwidthas the width to use for dates andlinesas the number of lines to use for each week.
      • year: The year you get the calendar for.
      • width: The width of dates in the output string.
      • lines The number of lines for each week.
      • space: The number of spaces between columns.
    • calendar.firstweekday(): Returns 0 if the current setting for the first weekday is Monday; returns 1 if the first weekday is Sunday in the current setting.
    • calendar.isleap(year): Returns True if the yearyearis a leap year; otherwise, returns False.
    • calendar.leapdays(start_year, end_year): Returns the number of leap days in the the years betweenstart_year(inclusive) andend_year(exclusive).
    • calendar.month(year, month[, width=0, lines=0]): Returns a string represented calendar for the monthmonthof the yearyear.
    • calendar.monthcalendar(year, month): Returns a list of nested lists. Each nested list represents a week. Each item in a nestlist represents a day of the monthmonth. The number for a day is set to 0 if the day is outside the monthmonthof the yearyear. The string is formatted withwidthas the width for dates andlinesas the number of lines for each week.
    • calendar.monthrange(year, month): Returns two integers. The first integer is the first weekday of the monthmonthin the yearyear. 0 represents Monday and 6 represents Sunday, and so on. The second integer is the number of days in the month.
    • calendar.prcal(year[, width=2, lines=1, space=6]): Different from calendar.calendar(year[,width=2,lines=1,space=6]), instead of returning a string representing the canlendar for the yearyear, it prints the calendar.
    • calendar.prmonth(year, month[, width=0, lines=0]): Different from calendar.month(year,month[,width, lines]), instead of returning a string representing the calendar for the monthmonth, it prints the calendar.
    • calendar.setfirstweekday(weekday): Sets the first day of each week to weekday in the range [0, 6]. 0 represents Monday and 6 represents Sunday.
    • calendar.timegm(tupletime): This function is the the inverse of time.gmtime([seconds]). It accepts a time instant in a time-tuple formtupletime and returns the number of seconds since the epoch of the same time instant.
    • calendar.weekday(year, month, day): Returns the weekday for the date.
  • time Module: The time module provides time related functions. To use the functions, useimport timeto import the module first.
    • time.altzone: Returns the number of seconds which is the offset of the daylight saving time in West Greenwich area. It returns negative if the area is in east of UTC.
    • time.gmtime([seconds]): Returns a time tuple for the specified time in seconds ifsecondsis given; otherwise, use the time in seconds since epoch.
    • time.asctime([tupletime]): Returns a 24-character string for the specified time tupletupletimeif it is given; otherwise, use the current local time.
    • time.clock(): Returns the current CPU time in seconds.
    • time.ctime([seconds]): Returns a 24-character string for the specified timesecondsin seconds since the epoch; otherwise, use the current local time.
    • time.localtime([seconds]): Returns a time-tuple with the local time for a specified time in seconds ifsecondsis given; otherwise, use the time in seconds since the epoch.
    • time.mktime(tupletime): Returns a floating-point value in seconds since the epoch for the time expressed as a specified time-tupletupletime.
    • time.sleep(seconds): Suspends the calling thread forsecondsseconds.
    • time.time(): Returns the current time as a floating-point number of seconds since the epoch.
  • datetime Module: datetime Object: The datetime module provides date, time, datetime, timedelta, tzinfo and timezone related functions. To use the functions, useimport timeto import the module first. This section only explains the functions under the datetime object.
    • astimezone([timezone_obj=None]): Return a datetime object according to the specified time zonetimezone_obj. Iftimezone_objis not given or None, returns the local date, time and time zone.
    • combine(date, time, tzinfo=self.tzinfo): Return a new datetime object that combines the given date objectdateand time objecttime. If the time zonetzinfo is provided, its value is used to set the tzinfo attribute of the result, otherwise, the tzinfo attribute of the time argumenttimeis used.
    • ctime(): Return a string representing the date and time. The output string will not include time zone information, regardless of whether the input is aware or naive.
    • date(year, month, day): Return a date object with the given year, month and day.
    • datetime(year, month, day[, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0]): Return a datetime object according to the given arguments.
    • dst(): If tzinfo is None, returns None, else returns self.tzinfo.dst(self), and raises an exception if the latter doesn’t return None or a timedelta object with magnitude less than one day.
    • isoformat([separate='T', timespec='auto']): Return a string representing the date and time in ISO 8601 format:
      • YYYY-MM-DDTHH:MM:SS.ffffff, if microsecond is not 0
      • YYYY-MM-DDTHH:MM:SS, if microsecond is 0
      • separate: Optional. It is a one-character separator placed between the date and time portions of the result.
      • timespec: Optional. It specifies the number of additional components of the time to include (the default is 'auto'). It can be one of the following:
        • 'auto': Same as 'seconds' if microsecond is 0; otherwise, same as 'microseconds'.
        • 'hours': Include the hour in the two-digit HH format.
        • 'minutes': Include hour and minute in HH:MM format.
        • 'seconds': Include hour, minute, and second in HH:MM:SS format.
        • 'milliseconds': Include full time, but truncate fractional second part to milliseconds. HH:MM:SS.sss format.
        • 'microseconds': Include full time in HH:MM:SS.ffffff format.
    • fromisoformat(date_string): Return a datetime corresponding to the date_stringdate_stringin one of the formats emitted by date.isoformat() and datetime.isoformat(). It is new in Python version 3.7.
    • fromordinal(ordinal): Return the datetime corresponding to the proleptic Gregorian ordinalordinalwhere January 1 of year 1 has ordinal 1. The hour, minute, second and microsecond of the result are all 0, and tzinfo is None.
    • fromtimestamp(timestamp[, tz=None]): Return the local date and time corresponding to the POSIX timestamp such as the timestamp returned by time.time(). If the optional argument tz is None or not given, the timestamptimestampis converted to the platform’s local date and time, and the returned datetime object is naive. Iftzis not None, it must be an instance of a tzinfo subclass, and the timestamptimestampis converted to tz’s time zone.
    • fromisocalendar(year, week, day): Return a datetime corresponding to the ISO calendar date specified by year, week and day. The non-date components of the datetime are populated with their normal default values.dayis a weekday from 1 to 7. This is the inverse of the function datetime.isocalendar().
    • isocalendar(): Return a named tuple with three components: year, week and weekday. The same as self.date().isocalendar().
    • isoweekday(): Return the day of the week as an integer, where Monday is 1 and Sunday is 7. The same as self.date().isoweekday().
    • now([tz=None]): Return the current local date and time. If the time zonetzis None or not given, this method works like the method today(). Iftzis not None, it must be an instance of a tzinfo subclass, and the current date and time are converted to tz’s time zone.
    • replace([year=self.year, month=self.month, day=self.day, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, *, fold=0]): Return a datetime with the same attributes, except for those attributes that are given new values by keyword arguments. Note that tzinfo=None can be specified to create a naive datetime from an aware datetime with no conversion of date and time data.
    • strftime(format): Return a string representing the date and time, controlled by the format stringformat. The following picture is taken from https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior. It is a list of all the format codes that the 1989 C standard requires, and these work on all platforms with a standard C implementation.
    • strptime(date_string, format): Return a datetime corresponding todate_string,parsed according to the formatformat.
    • time(): Return a datetime.time object with same hour, minute, second, microsecond and fold. tzinfo is None.
    • timedelta([days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0]): Return a timedelta object that represents a time duration.
    • timetuple(): Return a time.struct_time such as the one returned by time.localtime().
    • timetz(): Return a datetime.time object with same hour, minute, second, microsecond, fold, and tzinfo attributes except for those that are given new values by keyword arguments.
    • today(): Return the current local datetime, with tzinfo None.
    • toordinal(): Return the proleptic Gregorian ordinal of the date. The same as self.date().toordinal().
    • tzname(): If tzinfo is None, returns None, else returns self.tzinfo.tzname(self); raises an exception if it doesn’t return None or a string object.
    • utcfromtimestamp(timestamp): Return the UTC datetime corresponding to the POSIX timestamp, with tzinfo None. The returned datetime object is naive.
    • utcoffset(): If tzinfo is None, returns None, else returns self.tzinfo.utcoffset(self); raises an exception if it doesn’t return None or a timedelta object with magnitude less than one day.
    • utcnow(): Return the current UTC date and time as a naive datetime object, with tzinfo None.
    • weekday(): Return the day of the week as an integer, where Monday is 0 and Sunday is 6. The same as self.date().weekday(). See also isoweekday().