Summary of commonly used processing dates and times in Python

Keywords: Python Javascript

Python time module

In Python documents, time is classified in Generic Operating System Services. In other words, the functions it provides are closer to the operating system level. Reading through the document, we can see that the time module is carried out around Unix Timestamp.

Get current time and conversion time format

// time() returns the time in timestamp format (offset in seconds relative to 1.1 00:00:00)
>>> time.time()
1632643244.288437
// ctime() returns the time in string form. You can pass in the time stamp format for conversion
>>> time.ctime()
'Sun Sep 26 16:02:23 2021'
>>> time.ctime(time.time())
'Sun Sep 26 16:03:13 2021'

struct_time has 9 elements in total, of which the first 6 are year, month, day, hour, minute and second, and the last three respectively represent:
☆ tm_wday the day of the week (Sunday is 0)
☆ tm_ What day of the year is yday
☆ tm_ Is isdst daylight saving time

// Astime () returns the time in the form of string, which can be passed into struct_time is the form of time, which is used for conversion
>>> time.asctime()
'Sun Sep 26 16:03:35 2021'
>>> time.asctime(time.localtime())
'Sun Sep 26 16:03:52 2021'
// localtime() returns the struct of the current time_ Time format, which can be passed in timestamp format for conversion
>>> time.localtime()
time.struct_time(tm_year=2021, tm_mon=9, tm_mday=26, tm_hour=16, tm_min=4, tm_sec=16, tm_wday=6, tm_yday=269, tm_isdst=0)
>>> time.localtime(time.time())
time.struct_time(tm_year=2021, tm_mon=9, tm_mday=26, tm_hour=16, tm_min=5, tm_sec=1, tm_wday=6, tm_yday=269, tm_isdst=0)
// gmtime() returns the struct of the current time_ Time form, UTC time zone (0 time zone), can be passed in timestamp format time for conversion
>>> time.gmtime()
time.struct_time(tm_year=2021, tm_mon=9, tm_mday=26, tm_hour=8, tm_min=5, tm_sec=26, tm_wday=6, tm_yday=269, tm_isdst=0)
>>> time.gmtime(time.time())
time.struct_time(tm_year=2021, tm_mon=9, tm_mday=26, tm_hour=8, tm_min=5, tm_sec=42, tm_wday=6, tm_yday=269, tm_isdst=0)

Time formatting

// time.mktime() takes a struct_ Convert time format to timestamp
>>> time.mktime(time.localtime())
1632644087.0
// time.strftime(format[,t]) puts a struct_time time is converted to a formatted time string. If t is not specified, time.localtime() is passed in
>>> time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
'2021-09-26 16:16:25'
Symbolexplain
%cLocal corresponding date and time representation
%xLocal corresponding date
%XLocal corresponding time
%yRemove the year of the century (00 – 99)
%YFull year
%mMonth (01 – 12)
%bLocal simplified month name
%BLocal full month name
%dDay of the month (01 – 31)
%jDay of the year (001 – 366)
%UThe number of weeks in a year. (00 – 53 Sunday is the beginning of the week.)
%WIt is basically the same as% U, except that% W starts on Monday.
%wThe day of the week (0 – 6, 0 is Sunday)
%aLocal simplified week name
%ALocal full week name
%HThe hour of the day (24 hours, 00 – 23)
%IThe first few hours (12 hour system, 01 – 12)
%pThe corresponding character of local am or pm, "% p" is effective only when used with "% I".
%MMinutes (00 – 59)
%SSeconds (01 – 61). The document emphasizes that it is really 0 – 61, not 59. Leap year seconds account for two seconds
%ZThe name of the time zone (if no empty character exists)
%%'%' character

t PI DAR

time.sleep(): the thread delays running for the specified time. The unit is seconds.
time.clock(): it should be noted that this has different meanings on different systems. On UNIX systems, it returns the "process time", which is a floating-point number (timestamp) in seconds. In WINDOWS, the first call returns the actual running time of the process. The second call is the running time from the first call to the present. (in fact, it is based on QueryPerformanceCounter() on WIN32, which is more accurate than the representation of milliseconds)

Other built-in functions of time module

altzone(): returns the offset seconds of the daylight saving time region in Western Greenwich. If the region is east of Greenwich, it will return a negative value (such as Western Europe, including the UK). Only the region enabled for daylight saving time can be used.
tzset(): reinitialize the time related settings according to the environment variable TZ.

Python datetime module

date class

// max: the maximum date that the date object can represent
>>> print('date.max:', date.max)
date.max: 9999-12-31
// min: the minimum date that the date object can represent
>>> print('date.min:', date.min)
date.min: 0001-01-01
// resolution: the date object represents the smallest unit of the date. This is heaven
>>> print('date.resolution:', date.resolution)
date.resolution: 1 day, 0:00:00
// today(): returns a date object representing the current local date
>>> print('date.today():', date.today())
date.today(): 2021-09-26
// From time stamp (timestamp): returns a date object according to a given time stamp
>>> print('date.fromtimestamp():', date.fromtimestamp(time.time()))
date.fromtimestamp(): 2021-09-26

Instance methods and properties provided by date:

attributeexplain
.yearReturn year
.monthReturn month
.dayReturn day
.replace(year, month, day)Generate a new date object, and replace the attributes in the original object with the year, month and day specified by the parameter. (the original object remains unchanged)
.weekday()Return weekday. If it is Monday, return 0; If it is Tuesday, return 1, and so on
.isoweekday()Return weekday. If it is Monday, return 1; If it is Tuesday, return 2, and so on
.isocalendar()Return format, such as (year, wk num, wk day)
.isoformat()Returns a string in the format of 'YYYY-MM-DD'
.strftime(fmt)Custom format string. Similar to strftime in the time module.
.toordinal()Return the Gregorian Calendar date corresponding to the date

Example:

   from datetime import date

    today = date.today()
    print('today:', today)
    print('.year:', today.year)
    print('.month:', today.month)
    print('.replace():', today.replace(year=2017))
    print('.weekday():', today.weekday())
    print('.isoweekday():', today.isoweekday())
    print('.isocalendar():', today.isocalendar())
    print('.isoformat():', today.isoformat())
    print('.strftime():', today.strftime('%Y-%m-%d'))
    print('.toordinal():', today.toordinal())

result:

today: 2021-09-26
.year: 2021
.month: 9
.replace(): 2017-09-26
.weekday(): 6
.isoweekday(): 7
.isocalendar(): (2021, 38, 7)
.isoformat(): 2021-09-26
.strftime(): 2021-09-26
.toordinal(): 738059

Date also overloads some operations, which allows us to perform the following operations on the date:

date2 = date1 + timedelta # date plus an interval to return a new date object
date2 = date1 – timedelta # date minus an interval to return a new date object
timedelta = date1 – date2 # two dates are subtracted to return a time interval object
Date1 < date2 # two dates are compared

time class

Class properties defined by time class:

min,max: time Class can represent the minimum and maximum time. Among them, time.min = time(0, 0, 0, 0), time.max = time(23, 59, 59, 999999)
resolution: The smallest unit of time, here is 1 microsecond
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]]]]]): Create a new time object and replace the attributes in the original object with the hours, minutes, seconds and microseconds specified by the parameters (the original object remains unchanged);
.isoformat(): Return type, such as " HH:MM:SS"String representation of format;
.strftime(fmt): Returns a custom format string.

Like date, you can also compare two time objects or subtract to return a time interval object. No examples are provided here.

datetime class

datetime is a combination of date and time, including all information of date and time.
Class properties and methods defined by datetime class:

attributeexplain
minThe minimum value that datetime can represent
maxThe maximum value that datetime can represent
resolutiondatetime minimum unit
today()Returns a datetime object representing the current local time
now([tz])Returns a datetime object representing the current local time. If the parameter tz is provided, the local time of the time zone indicated by the tz parameter is obtained
utcnow()Returns a datetime object of the current utc time
fromtimestamp(timestamp[, tz])Create a datetime object according to the time. The parameter tz specifies the time zone information
utcfromtimestamp(timestamp)Create a datetime object based on time
combine(date, time)Create a datetime object based on date and time
strptime(date_string, format)Converts a format string to a datetime object

Example:

   from datetime import datetime
   import time

   print('datetime.max:', datetime.max)
   print('datetime.min:', datetime.min)
   print('datetime.resolution:', datetime.resolution)
   print('today():', datetime.today())
   print('now():', datetime.now())
   print('utcnow():', datetime.utcnow())
   print('fromtimestamp(tmstmp):', datetime.fromtimestamp(time.time()))
   print('utcfromtimestamp(tmstmp):', datetime.utcfromtimestamp(time.time()))

result:

datetime.max: 9999-12-31 23:59:59.999999
datetime.min: 0001-01-01 00:00:00
datetime.resolution: 0:00:00.000001
today(): 2021-09-26 17:51:10.105650
now(): 2021-09-26 17:51:10.105650
utcnow(): 2021-09-26 09:51:10.105650
fromtimestamp(tmstmp): 2021-09-26 17:51:10.106650
utcfromtimestamp(tmstmp): 2021-09-26 09:51:10.106650

timedelta class

The timedelta function returns a timedelta object, that is, an object representing a time interval.

import datetime

>>> print(datetime.datetime.today() - datetime.timedelta(10))
2021-09-16 18:01:34.757877

Posted by TheWart on Sun, 26 Sep 2021 02:19:02 -0700