Python’s time processing module is used more often in everyday use, but when using it, you basically have to look up the information, which is still a bit of a hassle, so comb through it to make it easier to use in the future.
Time-related concepts
Second At the 13th International Conference on Weights and Measures in 1967, it was decided to use the second, defined in atomic time, as the international standard unit of time: the duration of the 9,192,631,770 cycles of radiation corresponding to the leap between the two hyperfine energy levels of the cesium 133 atomic ground state, with the starting calendar element set at 0:00 on January 1, 1958.
An atomic clock is a clock that calculates and maintains accurate time using the atomic resonance frequency standard. The atomic clock is the most accurate time measurement and frequency standard known in the world.
GMT Greenwich Mean Time (GMT), is the standard time at the Royal Greenwich Observatory on the outskirts of London, as the prime meridian is defined as the line of longitude passing through there. GMT is also called Universal Time UT.
UTC Coordinated Universal Time (UTC), also known as Universal Standard Time, is based on the international atomic clock and has an error of a few nanoseconds per day. The second length of Coordinated Universal Time is the same as the second length of Atomic Time, and it is required to be as close as possible to UTC in terms of time (the difference between the two is kept within 0.9 seconds).
Leap seconds There are not only leap years, but also leap seconds. A leap second is an adjustment that adds or subtracts one second from Coordinated Universal Time at the end of the year or in the middle of the year (and possibly at the end of the quarter), as uniformly prescribed by the International Bureau of Weights and Measures, in order to keep Coordinated Universal Time close to the Universal Time moment. Due to the unevenness of the Earth’s rotation and long-term chronicity (mainly caused by tidal friction), it will make the difference between UTC (civil time) and atomic time exceed to ±0.9 seconds, then UTC will be set forward by 1 second (negative leap second, 59 seconds in the last minute) or backward by 1 second (positive leap second, 61 seconds in the last minute); leap seconds are usually added at the end of the Gregorian year or the end of June of the Gregorian calendar.
Time Zones are regions of the Earth that use the same definition of time. The relevant international conferences decided to divide the Earth’s surface into 24 time zones, from south to north, according to longitude lines, and to define the time difference between adjacent zones as 1 hour. When people cross a region, they correct their clocks by one hour (subtract one hour to the west and add one hour to the east), and add or subtract a few hours when they cross several regions. For example, if my country is in the eastern eight zone, it is expressed as GMT+8.
Daylight Saving Time (DST), also known as Daylight Saving Time, Daylight Saving Time or Summer Time. This is a system to save energy and artificially set the local time, in the summer time, the day time will be longer, so in order to save electricity, so in the summer time certain areas will set their time one hour earlier, that is, the original time zone is 8 o’clock well, but because the sun appears earlier in the summer, so move the time forward, in the original 8 o’clock, set as 9 o’clock of that day ( Time one hour earlier) ~ so that we can use the sun to illuminate, save the time spent on electricity, which is why it is called summer time savings!
Unix timestamp refers to the total number of seconds from 0:0:0 UTC on January 1, 1970 to the present, regardless of leap seconds.
Python time module
In the Python documentation, time is categorized under Generic Operating System Services, in other words, it provides functionality that is closer to the operating system level. As you can see from reading through the documentation, the time module is based around the Unix timestamp.
The module mainly consists of a class struct_time, several other functions and related constants. It is important to note that most of the functions in this module call the C library of the platform where they are located, so it is important to note that some functions are platform specific and may have different effects on different platforms. Another point is that, since it is based on Unix Timestamp, the date range is limited to 1970 - 2038, so if you write code that needs to handle dates outside the range described above, you may want to consider using the datetime module.
Get the current time and convert it to time format
- time() returns the time in timestamp format (offset in seconds relative to 1.1 00:00:00)
- ctime() returns the time in string form, you can pass in the time stamp format time, used for conversion
- asctime() returns the time in string form, you can pass in the struct_time form time, used for conversion
- localtime() returns the current time in struct_time form, can be passed in timestamp format and used to do the conversion
- gmtime() returns the current time in struct_time form, UTC time zone (0 time zone), can be passed in timestamp format time, used to do the conversion
|
|
struct_time has a total of 9 elements, of which the first 6 are the year, month, day, hour, minute and second, and the last three represent the following respectively
- tm_wday the first day of the week (Sunday is 0)
- tm_yday The first day of the year
- tm_isdst whether it is daylight saving time
Time formatting
time.mktime()
Convert a timestamp in struct_time format
time.strftime(format[,t]) Converts a struct_time time into a formatted time string. If t is not specified, it will be passed to time.localtime(). If any element of the tuple is out of bounds, a ValueError error will be thrown.
- %c local corresponding date and time representation
- %x local corresponding date
- %X local corresponding time
- %y The year with the century removed (00 - 99)
- %Y Complete year
- %m month (01 - 12)
- %b Local simplified month name
- %B Local full month name
- %d The first day of a month (01 - 31)
- %j Number of days in a year (001 - 366)
- %U Number of days of the week in a year. (00 - 53 Sundays are the beginning of a week.) All days before the first Sunday are placed in week 0.
- %W is basically the same as %U, except that %W starts a week with Monday.
- %w The first few days of a week (0 - 6, 0 being Sunday)
- %a Local (locale) simplified week name
- %A local complete week name
- %H The hour of the day (24-hour system, 00 - 23)
- %I The first few hours (12-hour system, 01 - 12)
- %p Local am or pm equivalent, “%p” only works in combination with “%I”.
- %M number of minutes (00 - 59)
- %S seconds (01 - 61), the documentation emphasizes that it is indeed 0 - 61, not 59, leap year seconds account for two seconds
- %Z Name of the time zone (null character if not present)
- %% ‘%’ character
time.strptime(string[,format])
Converts a formatted time string to struct_time. it is actually the inverse of strftime().
Timer function
time.sleep(secs)
The thread delays running for the specified amount of time. The unit is seconds.
time.clock()
Note that this means different things on different systems. On UNIX systems, it returns the “process time”, which is a floating point number (timestamp) expressed in seconds. In WINDOWS, the first call returns the actual time the process was running. The call after the second time is the running time from the first call to the present. (actually based on QueryPerformanceCounter() on WIN32, which is more accurate than millisecond representation)
The results of the run are.
where the first clock() output is the program run time, the second and third clock() output is the time interval with the first clock
Other built-in functions of the time module
- altzone() returns the number of seconds offset for the daylight saving time region west of Greenwich. If the region is east of Greenwich it will return a negative value (e.g. Western Europe, including the UK). Only available for daylight saving time enabled regions.
- tzset() reinitializes time-related settings based on the environment variable TZ.
The time module contains the attributes
- timezone is the local time zone (without daylight saving time) offset in seconds from Greenwich (>0, Americas; <=0 most of Europe, Asia, Africa).
- tzname contains a pair of strings that differ depending on the case, the name of the local time zone with daylight saving time and without.
Running results
datetime module
datetime is much more advanced than time, which can be understood as datetime is wrapped based on time and provides more useful functions.
The datetime module defines the following classes.
- date: A class that represents a date. Commonly used properties are year, month, day
- time: A class that represents time. Common properties are hour, minute, second, microsecond
- datetime: the date and time.
- timedelta: represents the time interval, i.e. the length between two points in time
- tzinfo: information related to the time zone
Note: All of these types of objects are immutable.
date class
The date class defines some common class methods and class properties:
- max, min: the maximum and minimum dates that the date object can represent
- resolution: the smallest unit in which the date object can represent the date. Here is the day
- today(): returns a date object that represents the current local date
- fromtimestamp(timestamp): return a date object based on the given time kill
- fromordinal(ordinal): converts Gregorian calendar time to a date object (not used for special calendars)
Implementation results.
The instance methods and properties provided by date.
- .year: returns the year
- .month: returns the month
- .day: return the day
- .replace(year, month, day): Generate a new date object, replacing the properties of the original object with the year, month, and day specified by the parameters. (The original object remains unchanged)
- .weekday(): return weekday, if it is Monday, return 0; if it is week 2, return 1, and so on
- .isoweekday(): return weekday, if it’s Monday, return 1; if it’s week 2, return 2, and so on
- .isocalendar(): return format like (year, wk num, wk day)
- .isoformat(): returns a string in format like ‘YYYY-MM-DD’
- .strftime(fmt): custom formatted string. Similar to strftime in the time module.
- .toordinal(): return the Gregorian Calendar date corresponding to the date
|
|
Implementation results.
date also overloads certain operations which allow us to do some of the following with dates.
- date2 = date1 + timedelta # date plus an interval, returning a new date object
- date2 = date1 - timedelta # date minus an interval, returning a new date object
- timedelta = date1 - date2 # two dates subtracted, return an interval object
- date1 < date2 # Two dates are compared
time class
The constructor for the time class is as follows: (where the parameter tzinfo, which represents the time zone information.)
class datetime.time(hour[, minute[, second[, microsecond[, tzinfo]]]])
Class properties defined by the time class.
- min, max: the minimum and maximum time that the time class can represent. where time.min = time(0, 0, 0, 0), time.max = time(23, 59, 59, 999999)
- resolution: the minimum unit of time, here is 1 microsecond
The time class provides instance methods and properties.
- .hour, .minute, .second, .microsecond: hour, minute, second, microsecond
- .tzinfo: time zone information
- .replace([hour[, minute[, second[, microsecond[, tzinfo]]]]]): creates a new time object, replacing the attributes in the original object with the hours, minutes, seconds, microseconds specified by the parameters (the original object remains unchanged).
- .isoformat(): return a string representation of the format “HH:MM:SS”.
- .strftime(fmt): returns a custom formatted string.
Like date, two time objects can be compared or subtracted to return a time interval object. No example will be provided here.
datetime class
datetime is the combination of date and time, including all information of date and time. Its constructor is as follows: datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]), the meaning of the parameters is the same as in the constructor of date and time, pay attention to the range of parameter values.
The datetime class defines the following class properties and methods.
- min, max: the minimum and maximum values that datetime can represent.
- resolution: the minimum unit of datetime.
- today(): returns a datetime object that represents the current local time.
- now([tz]): returns a datetime object that represents the current local time, and if the parameter tz is provided, gets the local time in the time zone referred to by the tz parameter; * utcnow(): returns a datetime object that represents the current local time.
- utcnow(): returns a datetime object representing the current utc time.
- fromtimestamp(timestamp[, tz]): creates a datetime object based on the time kill, with the parameter tz specifying the time zone information.
- utcfromtimestamp(timestamp): creates a datetime object based on the time kill.
- combine(date, time): creates a datetime object based on date and time.
- strptime(date_string, format): converts a format string to a datetime object.
|
|
Running results.
|
|
datetime class provides examples of methods and properties (many properties or methods have appeared in date and time, here have a similar meaning, here only list the names of these methods, the specific meaning will not be introduced one by one, you can refer to the above explanation of the date and time class. (For more details, please refer to the above explanation of date and time)
year, month, day, hour, minute, second, microsecond, tzinfo.
- date(): get the date object.
- time(): get time object.
- replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]]).
- timetuple()
- utctimetuple()
- toordinal()
- weekday()
- isocalendar()
- isoformat([sep])
- ctime(): returns a C-format string of the datetime, equivalent to ctime(time.mktime(dt.timetuple())).
- strftime(format)
Like date, it is possible to compare two datetime objects, either by subtracting them to return a time interval object, or by adding an interval to the datetime to return a new datetime object.
timedelta class
The timedelta function returns a timedelta object, which is an object that represents a time interval. The parameters of the function are shown below:
class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
There are no required parameters, but the first integer is the number of days in the interval if it is a simple control:
datetime.timedelta(10)
Two time interval objects can be added or subtracted from each other and still return a time interval object. And more convenient is a datetime object if you subtract a time interval object, then the return corresponds to the subtracted datetime object, and then two datetime objects if you subtract the return is a time interval object. This is very convenient.
tzinfo class
tzinfo is an abstract class and cannot be instantiated directly. It requires derived subclasses that provide the corresponding standard methods. datetime module does not provide any subclasses of tzinfo. The easiest way is to use the pytz module.
pytz module
pytz is a time zone processing module for Python (also includes daylight saving time). Before understanding the time zone processing module, you need to understand some time zone concepts.
To know the conversion relationship between time zones, it is actually very simple: subtract the local time from the local time zone, and what is left is Greenwich Mean Time. For example, 18:00 Beijing time is 18:00 + 08:00, and after subtracting that, it’s 10:00 + 00:00, so it’s 10:00 Greenwich Mean Time.
Python’s datetime can handle two types of time, offset-naive and offset-aware, the former being times that do not contain time zone information, and the latter being times that contain time zone information, and only times of the same type can be subtracted and compared.
The functions of the datetime module generate only offset-naive type datetime objects by default, such as now(), utcnow(), fromtimestamp(), utcfromtimestamp() and strftime(). Among them, now() and fromtimestamp() can accept a tzinfo object to generate a datetime object of type offset-aware, but the standard library does not provide any implemented tzinfo class, you have to implement it yourself.
The following is an example of a tzinfo class that implements Greenwich Mean Time and Beijing Time.
|
|
A tzinfo class needs to implement the 3 methods utcoffset, dst and tzname. Of these, utcoffset needs to return the time difference adjustment for summer time; tzname needs to return the time zone name, or not if you don’t need to use it.
Once a datetime object of type offset-aware is generated, we can call its astimezone() method to generate the time in other time zones (which will be calculated based on the time difference). And if we get a datetime object of type offset-naive, we can also call its replace() method to replace tzinfo, but this replacement will not adjust other time properties according to the time difference. So, if you get a datetime object of offset-naive type with Greenwich Mean Time, you can call replace(tzinfo=UTC()) directly to convert it to offset-aware type, and then call astimezone() to generate datetime objects of other time zones.
It all looks very simple, but I don’t know if you still remember the summer time zone mentioned above. When it comes to summer time, it really gives me a headache because there are no rules to follow: some countries have summer time, some countries don’t, some countries only have summer time in some areas, some areas only have summer time in some years, the start and end of summer time in each area are not necessarily the same, and some places don’t use the fucking days of the month to specify the start and end of summer time, but use In some places, TMD does not specify the start and end of summer season in terms of days of the month, but in terms of days of the week.
The pytz module, using the Olson TZ Database, solves the problem of consistency of time zone calculation across platforms, and solves the calculation problems caused by daylight saving time. Since countries and regions can choose their own time zones and whether or not to use daylight saving time, the pytz module can update its own time zone and daylight saving time related information if needed.
pytz provides full timezone information, such as
Running results.
If you need to get the time zone of a country, you can use the following.
Implementation results.
|
|
China one has two time zones, one for Shanghai and one for Urumqi, let’s see what we have the difference between.
Implementation results.
You can see that Shanghai is the eighth eastern district, while Urumqi is the sixth eastern district.
Time zone conversion
The operation has but a relatively simple interchange of local time zone and UTC.
Implementation results.
Time zone to time zone conversion is possible using astimezone().
|
|
Implementation results.
Alternatively you can use replace to modify the time zone with an extra 6 minutes (do not use). The specific reasons are.
17 years of the Republic of China (1928), the Nationalist government unified China, the former Central Observatory’s business by the Nanjing government Central Research Institute of Astronomy and Meteorological Research Institute received respectively. Astronomical Research Institute compiled the calendar basically follow the practice of the Central Observatory, the country is still divided into five standard time zones, only in relation to the intersection of gas, the conjunction of the first day, the sun’s time, etc., no longer use the local equinox in Beiping, but to Nanjing is located in the standard time zone of the regional time that is 120 ° East longitude standard time instead. There is a difference of 352 seconds between the local equinox of Beiping and 120°E Standard Time.
Implementation results.
Daylight saving time processing
Due to the relatively small number of scenarios used, no detailed study is done.
dateutil module
Install the module: pip install python-dateutil
parser.parse()
Parse time to datetime format, support most time strings. The default is 0:00 if no time is specified, today if no date is specified, and this year if no year is specified.
|
|
Implementation results.
rrule.rrule()
Main function: generate date and time according to the rules. The function prototype is as follows.
rrule(self, freq, dtstart=None, interval=1, wkst=None, count=None, until=None, bysetpos=None, bymonth=None, bymonthday=None, byyearday=None, byeaster=None, byweekno=None, byweekday=None, byhour=None, byminute=None, bysecond=None, cache=False)
where.
- freq: can be interpreted as units. It can be YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY, i.e. year, month, week, hour, minute and second.
- dtstart,until: is the start and end time.
- wkst:Week start time.
- interval:interval.
- count:Specifies how many to generate.
- byxxx:Specify the matching period. For example, byweekday=(MO,TU) then only Monday-Tuesday matches. byweekday can specify MO,TU,WE,TH,FR,SA,SU. i.e. Monday to Sunday.
For more reference: http://dateutil.readthedocs.io/en/stable/index.html
Arrow
Arrow provides a friendly and very easy to understand method for creating times, calculating times, formatting times, and doing conversions, extractions, and compatibility with python datetime types. It includes the dateutil module, and according to its documentation Arrow is designed “to help you handle dates and times with less code”.
UTC time
Use the utcnow() function to create the UTC time.
Using the to() method, we convert the UTC time to local time.
Local time
Local time is the time in a specific region or time zone.
Use the now() function to create a local time. The to() method is used to convert the local time to UTC time.
Parsing time
The get() method is used to parse the time.
This example parses time from date and time strings and timestamps.
Unix timestamps
This example displays the local time and the Unix time. It then converts the Unix time back to the date object.
Using the fromtimestamp() method, we convert the Unix time back to the Arrow date object.
You can also format the date to Unix time.
By passing the ‘X’ specifier to the format() method, we print the current local date as Unix time.
Formatting the date and time
The date and time can be formatted with the format() method.
|
|
Format description.
Convert to regional time
Working days
The weekday() or format() method can be used to find the weekday of the date.
Move time
The shift() method is used to move the time.
Daylight Saving Time
This example uses dst() to display daylight saving time.
Humanized date and time
On social networking sites, we often see terms such as “one hour ago” or “5 minutes ago” that provide quick information about when a post was created or modified. Arrow includes the humanize() method to create such terms.
ISO 8601 class
The international standard ISO 8601, which is the International Organization for Standardization’s representation of date and time, is called “Data storage and exchange forms - Information exchange - Representation of date and time”, and is more involved in API interface development.
|
|
Or use the following parsing.
|
|
Also use the iso8601 module: http://pyiso8601.readthedocs.io/en/latest/
Other date and time tools.
- Gregorian calendar to lunar calendar: https://pypi.python.org/pypi/LunarSolarConverter/
- Verbalized dates: https://github.com/scrapinghub/dateparser
- Moment: https://github.com/zachwill/moment
- Delorean: https://github.com/myusuf3/delorean
- When: https://whenpy.readthedocs.io/en/latest/
- Pendulum: https://pendulum.eustace.io/
- Time Machine: https://github.com/spulec/freezegun
- Work Calendar: https://github.com/peopledoc/workalendar
- Chinese Legal Holidays: https://github.com/NateScarlet/holiday-cn