Python datetime processing time summary

Python provides multiple built-in modules for manipulating date and time, such as calendar, time, datetime. I have already introduced the time module in the previous article. The interface it provides is basically the same as the C standard library time.h. Compared with the time module, the interface of the datetime module is more intuitive and easier to call. Let's talk about the datetime module today.

The datetime module defines two constants: datetime.MINYEAR and datetime.MAXYEAR, which respectively represent the minimum and maximum years that datetime can represent. Among them, MINYEAR = 1, MAXYEAR = 9999. (For even players, this range is enough~~)

The datetime module defines the following classes:

Note: These types of objects are immutable.

The following details the usage of these classes.

date class

The date class represents a date. The date consists of year, month, and day (everyone on earth knows it~~). The constructor of the date class is as follows:

class datetime.date(year, month, day): The meaning of the parameters will not be explained, but there are a few points to note:

The date class defines some commonly used class methods and class attributes to facilitate our operations:

Examples of use:

from datetime import*import time
 
print 'date.max:', date.max
print 'date.min:', date.min
print 'date.today():', date.today()
print 'date.fromtimestamp():', date.fromtimestamp(time.time())
 
# # - - - - result----
# date.max:9999-12-31
# date.min:0001-01-01
# date.today():2010-04-06
# date.fromtimestamp():2010-04-06

Instance methods and attributes provided by date:

Examples of use:

now =date(2010,04,06)
tomorrow = now.replace(day =07)
print 'now:', now,', tomorrow:', tomorrow
print 'timetuple():', now.timetuple()
print 'weekday():', now.weekday()
print 'isoweekday():', now.isoweekday()
print 'isocalendar():', now.isocalendar()
print 'isoformat():', now.isoformat()
 
# # - - - - result----
# now:2010-04-06, tomorrow:2010-04-07
# timetuple():(2010,4,6,0,0,0,1,96,-1)
# weekday():1
# isoweekday():2
# isocalendar():(2010,14,2)
# isoformat():2010-04-06

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

Note: When operating on the date, prevent the date from exceeding the range it can represent.

Examples of use:

now = date.today()
tomorrow = now.replace(day =7)
delta = tomorrow - now
print 'now:', now,' tomorrow:', tomorrow
print 'timedelta:', delta
print now + delta
print tomorrow   now
 
# # - - - - result----
# now:2010-04-06 tomorrow:2010-04-07
# timedelta:1 day,0:00:00
# 2010-04-07
# True

Time class

The time class represents time, consisting of hours, minutes, seconds, and microseconds. (I'm not from Mars~~) The constructor of the time class is as follows:

class datetime.time(hour[, minute[, second[, microsecond[, tzinfo]]]]): The meaning of each parameter is not explained, here pay attention to the parameter tzinfo, which represents time zone information. Note the value range of each parameter: the range of hour is [0, 24), the range of minute is [0, 60), the range of second is [0, 60), and the range of microsecond is [0, 1000000).

Class attributes defined by the time class:

The instance methods and attributes provided by the time class:

Examples of use:

from datetime import*
tm =time(23,46,10)
print 'tm:', tm
print 'hour: %d, minute: %d, second: %d, microsecond: %d'/%(tm.hour, tm.minute, tm.second, tm.microsecond)
tm1 = tm.replace(hour =20)
print 'tm1:', tm1
print 'isoformat():', tm.isoformat()
 
# # - - - - result----
# tm:23:46:10
# hour:23, minute:46, second:10, microsecond:0
# tm1:20:46:10
# isoformat():23:46:10

Like date, two time objects can also be compared or subtracted to return a time interval object. No examples are provided here.

datetime class

Datetime is a combination of date and time, including all information about date and time. Its constructor is as follows: datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]), the meaning of each parameter is the same as in the date and time constructor Similarly, pay attention to the range of parameter values.

Class attributes and methods defined by the datetime class:

Examples of use:

from datetime import*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-3123:59:59.999999
# datetime.min:0001-01-0100:00:00
# datetime.resolution:0:00:00.000001
# today():2010-04-0709:48:16.234000
# now():2010-04-0709:48:16.234000
# utcnow():2010-04-0701:48:16.234000 #China is located+8 hours, 8 different from local time
# fromtimestamp(tmstmp):2010-04-0709:48:16.234000
# utcfromtimestamp(tmstmp):2010-04-0701:48:16.234000

The instance methods and attributes provided by the datetime class (many attributes or methods have appeared in date and time, and have similar meanings here. Only the method names are listed here. The specific meanings will not be introduced one by one. You can refer to the above on date Explanation with time class.):

Like date, you can also compare two datetime objects, or subtract to return a time interval object, or date and time plus an interval to return a new date time object. A detailed example is not provided here, please try it yourself~~

Format string

datetime, date, and time all provide the strftime() method, which receives a format string and outputs the string representation of the date and time. The following table is pulled from the python manual, I have carried out a simple translation of some (the translation is a bit awkward~~).

Format character meaning

Shorthand for %a week. If Wednesday is Web
%A Full text of the week. Such as Wednesday is Wednesday
Shorthand for %b month. For example, April is Apr
%B is the full name of the month. For example, April is April
%c: String representation of date and time. (Eg: 04/07/10 10:43:39)
%d: the number of days in the month (the day of the month)
%f: microseconds (range [0,999999])
%H: hour (24-hour clock, [0, 23])
%I: hour (12-hour clock, [0, 11])
%j: the number of days in the year [001,366] (the day of the year)
%m: month ([01,12])
%M: minutes ([00,59])
%p: AM or PM
%S: seconds (the range is [00,61], why not [00, 59], refer to the python manual~_~)
%U: The number of weeks in the current year, the week number of the year), and Sunday is the first day of the week
%w: Today is the number of days in this week, the range is [0, 6], 6 means Sunday
%W: Week number of the current year (it is the first few weeks of the current year), and Monday is the first day of the week
%x: date string (eg: 04/07/10)
%X: Time string (eg: 10:43:39)
%y: year represented by 2 digits
%Y: year represented by 4 digits
%z: interval with UTC time (if it is local time, return an empty string)
%Z: Time zone name (if it is local time, return an empty string)
%%:%% = %

example:

dt = datetime.now()
print '(%Y-%m-%d %H:%M:%S %f): ', dt.strftime('%Y-%m-%d %H:%M:%S %f')
print '(%Y-%m-%d %H:%M:%S %p): ', dt.strftime('%y-%m-%d %I:%M:%S %p')
print '%%a: %s '% dt.strftime('%a')
print '%%A: %s '% dt.strftime('%A')
print '%%b: %s '% dt.strftime('%b')
print '%%B: %s '% dt.strftime('%B')
print 'Date time%%c: %s '% dt.strftime('%c')
print 'date%%x:%s '% dt.strftime('%x')
print 'time%%X:%s '% dt.strftime('%X')
print 'Today is the first of this week%s days'% dt.strftime('%w')
print 'Today is the first of this year%s days'% dt.strftime('%j')
print 'This week is the first of the year%s week'% dt.strftime('%U')
 
# # - - - - result----
# ( %Y-%m-%d %H:%M:%S %f):2010-04-0710:52:18937000
# ( %Y-%m-%d %H:%M:%S %p):10-04-0710:52:18 AM
# %a: Wed 
# %A: Wednesday 
# %b: Apr 
# %B: April 
# Date time%c:04/07/1010:52:18 
# date%x:04/07/10 
# time%X:10:52:18 
# Today is the 3rd day of the week
# Today is the 097th day of the year
# This week is the 14th week of the year

This is the end of this article on python datetime processing time summary. For more related python datetime processing time content, please search ZaLou.Cn

Recommended Posts

Python datetime processing time summary
Python processing json summary
python_ file processing
Summary of common operations of Python time module
Python basic summary
Python interview questions summary
Python advanced usage summary
Python high-order function usage summary!
Python on image processing PIL
python3 records program running time
LeetCode brushing questions summary python3
Python high-order function usage summary!
Summary of logarithm method in Python
Python list comprehension operation example summary
Python PIL library image graying processing
A summary of 200 Python standard libraries!
Python processing PDF and CDF examples
Summary of Python calling private attributes
Python decorator simple usage example summary