Python module learning notes--time and datatime
Python provides multiple built-in modules for date and time operations, such as calendar, time, and datetime. First, we will introduce the most commonly used functions in the time module. The interfaces provided by this module are basically the same as those provided by the C standard library time. h. Then we will introduce the datatime module. Compared with the time module, the datetime Module Interface is more intuitive and easier to call.
Time Module
Time. time
The time. time () function returns the number of seconds since January 1, January 1, 1970. This is a floating point number.
import timeprint time.time()
Vc/W1Nq1xMPryv2jrMbkvqvIt7bIuN/T2jHOosProaO/ydLUyrnTw7jDuq/K/fingerprint + DQo8cHJlIGNsYXNzPQ = "brush: java;">import timeprint time.clock()time.sleep(2)print time.clock()time.sleep(3)print time.clock()
Time. gmtime
This function is prototype: time. gmtime ([sec]). The optional parameter sec indicates the number of seconds since January 1. The default value is time. time (). The function returns an object of the time. struct_time type (struct_time is the object that represents time defined in the time module ).
import timeprint time.gmtime() print time.gmtime(time.time() - 24 * 60 * 60)
Time. localtime
Time. localtime is very similar to time. gmtime. It also returns a struct_time object, which can be viewed as a localized version of gmtime.
Time. mktime
Time. mktime: opposite to gmtime () and localtime (), it receives the struct_time object as a parameter and returns a floating point number that represents the time in seconds.
import timeprint time.mktime(time.localtime())print time.time()
Time. strftime
Time. strftime converts a date to a string representation. Its function prototype is time. strftime (format [, t]). The format parameter is a format string (for details about the format string, refer to time. strftime). The optional parameter t is a struct_time object.
import timeprint time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())print time.strftime('Weekday: %w; Day of the yesr: %j')
Time. strptime
Parses a time string in the specified format and returns the struct_time object. This function is prototype: time. strptime (string, format). Both parameters are strings.
import timeprint time.strptime('201-06-23 15:30:53', '%Y-%m-%d %H:%M:%S')
The above are only the most common methods in the time module. There are many other methods such as time. timezone, time. tzname... For more information about shoes, see the time module in the Python manual.
Datetime Module
The datetime module defines two constants: datetime. MINYEAR and datetime. MAXYEAR, which respectively indicate the minimum and maximum years that datetime can represent. MINYEAR = 1, MAXYEAR = 9999.
The datetime module defines the following classes:
-Datetime. date: indicates the date class. Common attributes include year, month, and day;
-Datetime. time: indicates the time class. Common attributes include hour, minute, second, And microsecond;
-Datetime. datetime: indicates the date and time.
-Datetime. timedelta: indicates the time interval, that is, the length between two time points.
-Datetime. tzinfo: Time Zone-related information. (This class is not fully discussed here. For more information about children's shoes, see the python manual)
[Note] the above types of objects are immutable.
Date class
The date class represents a date. The constructor is as follows:
class datetime.date(year, month, day)
The range of year is [MINYEAR, MAXYEAR], that is, [1, 9999];
The range of month is [1, 12];
The maximum value of day is determined by the given year and month parameters. The leap year has 29 days in January.
The date class defines some common class methods and class attributes for our convenience:
-Date. max and date. min: the maximum and minimum dates that can be expressed by the date object;
-Date. resolution: The minimum unit of the date object. Here is the day.
-Date. today (): returns a date object that represents the current local date;
-Date. fromtimestamp (timestamp): returns a date object based on the given time period;
-Datetime. fromordinal (ordinal): converts a Gregorian Calendar time to a date object .)
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())
Date provides the following instance methods and attributes:
-Date. year, date. month, date. day: year, month, and day;
-Date. replace (year, month, day): generates a new date object, replacing the attributes of the original object with the year, month, and day specified by the parameter.
-Date. timetuple (): returns the time. struct_time object corresponding to the date;
-Date. toordinal (): returns the Gregorian Calendar date corresponding to the date;
-Date. weekday (): returns weekday. If it is Monday, 0 is returned. If it is day 2, 1 is returned, and so on;
-Data. isoweekday (): returns weekday. If it is Monday, 1 is returned. If it is day 2, 2 is returned, and so on;
-Date. isocalendar (): returns the tuples in the format of (year, month, day;
-Date. isoformat (): returns a string in the format of 'yyyy-MM-DD;
-Date. strftime (fmt): Custom formatted string.
from datetime import * now = date(2015,6,10)tomorrow = now.replace(day = 11)print 'now:',now, ', tomorrow:',tomorrowprint 'timetuple():', now.timetuple()print 'weekday():', now.weekday()print 'isoweekday():', now.isoweekday()print 'isocalendar():', now.isocalendar()print 'isoformat():', now.isoformat()
Date also reloads some operations to allow the following operations on the date:
-Date2 = date1 + timedelta # date plus an interval, a new date object is returned (timedelta will be described below, indicating the interval)
-Date2 = date1-timedelta # Return a new date object at the date interval.
-Timedelta = date1-date2 # subtract two dates and return a time interval object
Date1 <date2 # compare two dates
[Note] When performing operations on a date, you must prevent the date from exceeding the range it can represent.
from datetime import * now = date.today()tomorrow = now.replace(day = 11)delta = tomorrow - nowprint 'now:', now, ' tomorrow:', tomorrowprint 'timedelta:', deltaprint now + deltaprint tomorrow > now
Time class
The time class indicates the time, which consists of hour, minute, second, And microsecond. The constructor of the time class is as follows:
class datetime.time(hour[, minute[, second[, microsecond[, tzinfo]]]])
The tzinfo parameter indicates the time zone information. Value range of each parameter: hour is in the range of [0, 24), minute is in the range of [0, 60), and second is in the range of [0, 60 ), the microsecond range is [0, 1000000 ).
Class attributes defined by the time class:
-Time. min and time. max: Minimum and maximum time that can be expressed by the time class. Time. min = time (0, 0, 0, 0), time. max = time (23, 59, 59,999 999 );
-Time. resolution: minimum unit of time, which is 1 microsecond;
Instance methods and Attributes provided by the time class:
-Time. hour, time. minute, time. second, time. microsecond: hour, minute, second, microsecond;
-Time. tzinfo: time Zone information;
-Time. replace ([hour [, minute [, second [, microsecond [, tzinfo]): Creates a new time object, replace the attribute in the original object with the time, minute, second, And microsecond specified by the parameter (the original object remains unchanged );
-Time. isoformat (): returns a string representation in the format of "HH: MM: SS;
-Time. strftime (fmt): returns a custom formatted string.
from datetime import * tm = time(7, 17, 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 = 8) print 'tm1:', tm1 print 'isoformat():', tm.isoformat()
Like date, time can also compare two time objects, or subtract to return a time interval object.
Datetime type
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 meanings of parameters are the same as those in the constructors of date and time. Pay attention to the parameter value range.
The class attributes and methods defined by the datetime class:
-Datetime. min and datetime. max: minimum and maximum values that datetime can represent;
-Datetime. resolution: The minimum unit of datetime;
-Datetime. today (): returns a datetime object that represents the current local time;
-Datetime. now ([tz]): returns a datetime object that represents the current local time. If the parameter tz is provided, the local time indicated by the tz parameter is obtained;
-Datetime. utcnow (): returns a datetime object of the current utc time;
-Datetime. fromtimestamp (timestamp [, tz]): Creates a datetime object based on the time period. The parameter tz specifies the time zone information;
-Datetime. utcfromtimestamp (timestamp): Creates a datetime object based on the time limit;
-Datetime. combine (date, time): Creates a datetime object based on date and time;
-Datetime. strptime (date_string, format): converts a format string to a datetime object;
from datetime import * import timeprint '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())
The instance methods and Attributes provided by the datetime class (many attributes or methods have already appeared in date and time, refer to the above ):
-Datetime. year, month, day, hour, minute, second, microsecond, and tzinfo:
-Datetime. date (): obtains the date object;
-Datetime. time (): obtains the time object;
-Datetime. replace ([year [, month [, day [, hour [, minute [, second [, microsecond [, tzinfo]):
-Datetime. timetuple ()
-Datetime. utctimetuple ()
-Datetime. toordinal ()
-Datetime. weekday ()
-Datetime. isocalendar ()
-Datetime. isoformat ([sep])
-Datetime. ctime (): returns a C-format string of the date and time, which is equivalent to time. ctime (time. mktime (dt. timetuple ()));
Datetime. strftime (format)
Like date, you can also compare two datetime objects, or subtract to return a time interval object, or add an interval to return a new date and time object.
Format String
The strftime () method is provided for datetime, date, and time. This method receives a format string and outputs a string representation of the date and time.
Format characters |
Meaning |
% |
Abbreviation of the week, for example, Wednesday is Web |
% |
Full weekly, such as Wednesday. |
% B |
Abbreviated month, for example, Apr in February |
% B |
Full write of the month. For example, if February is else l |
% C |
String Representation of the date and time. (For example, 04/07/10 10:43:39) |
% D |
The day of the month (the day of the month) |
% F |
Microseconds (range: []) |
% H |
Hour (in 24-hour format, [0, 23]) |
% I |
Hour (in 12-hour format, [0, 11]) |
% J |
The number of days in the year [001,366] (the day of the year) |
% M |
Month ([]) |
% M |
Minutes ([]) |
% P |
AM or PM |
% S |
Second (range: []) |
% U |
The week is the week of the current year, and Sunday is the first day of the week. |
% W |
The number of days of today in this week. The value range is [0, 6]. 6 indicates Sunday. |
% W |
The number of weeks in the current year (the week of the current year), and Monday as the first day of the week |
% X |
Date string (for example: 04/07/10) |
% X |
Time string (for example, 10: 43: 39) |
% Y |
The year represented by two numbers. |
% Y |
The year represented by four numbers. |
% Z |
The time interval from utc (if the local time is used, an empty string is returned) |
% Z |
Time zone name (if it is a local time, an empty string is returned) |
% |
% => % |
From datetime import * import timedt = 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 and time % c: % s' % dt. strftime ('% C') print' date % x: % s' % dt. strftime ('% x') print' time % x: % s' % dt. strftime ('% x') print' today is the % s day of the week '% dt. strftime ('% W') print' today is the % s day of this year '% dt. strftime ('% J') print' this week is the % s week of this year '% dt. strftime ('% U ')