time — Time Classes and Functions#

Time handling module.

Added in version 7.5.

Imports in pywikibot module

The following class is imported in time module but can also be used as pywikibot members:

pywikibot.time.MW_KEYS = mappingproxy({'s': 'seconds', 'h': 'hours', 'd': 'days', 'w': 'weeks', 'y': 'years'})#

Added in version 7.5.

class pywikibot.time.TZoneFixedOffset(offset, name)[source]#

Bases: tzinfo

Class building tzinfo objects for fixed-offset time zones.

Parameters:
  • offset (int) – a number indicating fixed offset in minutes east from UTC

  • name (str) – a string with name of the timezone

dst(dt)[source]#

Return no daylight savings time.

Parameters:

dt (datetime | None)

Return type:

timedelta

tzname(dt)[source]#

Return the name of the timezone.

Parameters:

dt (datetime | None)

Return type:

str

utcoffset(dt)[source]#

Return the offset to UTC.

Parameters:

dt (datetime | None)

Return type:

timedelta

class pywikibot.time.Timestamp[source]#

Bases: datetime

Class for handling MediaWiki timestamps.

This inherits from datetime.datetime, so it can use all of the methods and operations of a datetime object. To ensure that the results of any operation are also a Timestamp object, be sure to use only Timestamp objects (and datetime.timedelta) in any operation.

Use Timestamp.fromISOformat() and Timestamp.fromtimestampformat() to create Timestamp objects from MediaWiki string formats. As these constructors are typically used to create objects using data passed provided by site and page methods, some of which return a Timestamp when previously they returned a MediaWiki string representation, these methods also accept a Timestamp object, in which case they return a clone.

Alternatively, Timestamp.set_timestamp() can create Timestamp objects from Timestamp, datetime.datetime object, or strings compliant with ISO8601, MediaWiki, or POSIX formats.

Use Site.server_time() for the current time; this is more reliable than using Timestamp.utcnow() or Timestamp.nowutc().

Changed in version 7.5: moved to time module

ISO8601Format#

classproperty ISO8601 format string class property for compatibility purpose.

Return type:

str

clone()[source]#

Clone this instance.

Deprecated since version 8.0: Use replace() method instead.

Return type:

Timestamp

classmethod fromISOformat(ts, sep='T')[source]#

Convert an ISO 8601 timestamp to a Timestamp object.

Parameters:
  • ts (str | Timestamp) – ISO 8601 timestamp or a Timestamp object already

  • sep (str) – one-character separator, placed between the date and time

Returns:

Timestamp object

Return type:

Timestamp

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

Return the local date and time corresponding to the POSIX ts.

This class method is for Python 3.7 to upcast the class if a tz is given.

Added in version 9.0.

Parameters:

timestamp (int | float)

Return type:

Timestamp

classmethod fromtimestampformat(ts, strict=False)[source]#

Convert a MediaWiki internal timestamp to a Timestamp object.

Changed in version 3.0: create a Timestamp if only year, month and day are given.

Changed in version 8.0: the strict parameter was added which discards missing element tolerance.

Example

>>> Timestamp.fromtimestampformat('20220705082234')
Timestamp(2022, 7, 5, 8, 22, 34)
>>> Timestamp.fromtimestampformat('20220927')
Timestamp(2022, 9, 27, 0, 0)
>>> Timestamp.fromtimestampformat('20221109', strict=True)
Traceback (most recent call last):
...
ValueError: time data '20221109' does not match MW format.
param ts:

the timestamp to be converted

param strict:

If true, do not ignore missing timestamp elements for hours, minutes or seconds

return:

return the Timestamp object from given ts.

raises ValueError:

The timestamp is invalid, e.g. missing or invalid timestamp component.

Parameters:
Return type:

Timestamp

isoformat(sep='T')[source]#

Convert object to an ISO 8601 timestamp accepted by MediaWiki.

datetime.datetime.isoformat does not postfix the ISO formatted date with a ‘Z’ unless a timezone is included, which causes MediaWiki ~1.19 and earlier to fail.

Parameters:

sep (str)

Return type:

str

mediawikiTSFormat = '%Y%m%d%H%M%S'#
classmethod now(tz=None)[source]#

Return the current local date and time.

This class method is for Python 3.7 to upcast the class if a tz is given.

Added in version 9.0.

See also

Return type:

Timestamp

classmethod nowutc(*, with_tz=True)[source]#

Return the current UTC date and time.

If with_tz is True it returns an aware Timestamp object with UTC timezone by calling now(datetime.UTC). As such this is just a short way to get it.

Otherwise the UTC timestamp is returned as a naive Timestamp object with timezone of None. This is equal to the Timestamp.utcnow().

Warning

Because naive datetime objects are treated by many datetime methods as local times, it is preferred to use aware Timestamps or datetimes to represent times in UTC. As such, it is not recommended to set with_tz to False.

Caution

You cannot compare, add or subtract offset-naive and offset- aware Timestamps/datetimes (i.e. missing or having timezone). A TypeError will be raised in such cases.

Added in version 9.0.

Parameters:

with_tz (bool) – Whether to include UTC timezone or not

Return type:

Timestamp

posix_timestamp()[source]#

Convert object to a POSIX timestamp.

See Note in datetime.timestamp().

Added in version 7.5.

Return type:

float

posix_timestamp_format()[source]#

Convert object to a POSIX timestamp format.

Added in version 7.5.

Return type:

str

classmethod set_timestamp(ts)[source]#

Set Timestamp from input object.

ts is converted to a datetime naive object representing UTC time. String shall be compliant with:

  • Mediwiki timestamp format: YYYYMMDDHHMMSS

  • ISO8601 format: YYYY-MM-DD[T ]HH:MM:SS[Z|±HH[MM[SS[.ffffff]]]]

  • POSIX format: seconds from Unix epoch S{1,13}[.ffffff]]

Added in version 7.5.

Changed in version 8.0: raises TypeError instead of ValueError.

Parameters:

ts (str | datetime | Timestamp) – Timestamp, datetime.datetime or str

Returns:

Timestamp object

Raises:

TypeError – conversion failed

Return type:

Timestamp

totimestampformat()[source]#

Convert object to a MediaWiki internal timestamp.

Return type:

str

classmethod utcnow()[source]#

Return the current UTC date and time, with tzinfo None.

This is like Timestamp.now(), but returns the current UTC date and time, as a naive Timestamp object. An aware current UTC datetime can be obtained by calling Timestamp.nowutc().

Note

This method is deprecated since Python 3.12 but held here for backward compatibility because utcnow is widely used inside the framework to compare MediaWiki timestamps which are UTC-based. Neither datetime.fromisoformat() implementations of Python < 3.11 nor Timestamp specific fromISOformat() supports timezone.

Warning

Because naive datetime objects are treated by many datetime methods as local times, it is preferred to use aware Timestamps or datetimes to represent times in UTC. As such, the recommended way to create an object representing the current time in UTC is by calling Timestamp.nowutc().

Hint

This method might be deprecated later.

Added in version 9.0.

Return type:

Timestamp

pywikibot.time.parse_duration(string)[source]#

Return the key and duration extracted from the string.

Parameters:

string (str) – a string defining a time period

Return type:

tuple[str, int]

Examples:

300s - 300 seconds
36h - 36 hours
7d - 7 days
2w - 2 weeks (14 days)
1y - 1 year
Returns:

key and duration extracted form the string

Parameters:

string (str)

Return type:

tuple[str, int]

pywikibot.time.str2timedelta(string, timestamp=None)[source]#

Return a timedelta for a shorthand duration.

Parameters:
  • string (str) – a string defining a time period:

  • timestamp (datetime | None)

Return type:

timedelta

Examples:

300s - 300 seconds
36h - 36 hours
7d - 7 days
2w - 2 weeks (14 days)
1y - 1 year
Parameters:
  • timestamp (datetime.datetime) – a timestamp to calculate a more accurate duration offset used by years

  • string (str)

Returns:

the corresponding timedelta object

Return type:

timedelta