Python provides several built-in modules for manipulating date times, like Calendar,time,datetime. First, a few of the most commonly used functions in the time module are described, and the interface provided is basically consistent with the C standard library time.h. Then introduce the Datatime module, the interface of the DateTime module is more intuitive and easier to invoke than the time module.
Time Module
Time.time
The Time.time () function returns the number of seconds since January 1, 1970, which is a floating point.
import timeprint time.time()
Time.sleep
You can suspend the current process by calling Time.sleep. Time.sleep receives a floating-point parameter, in seconds, indicating the time the process was suspended.
Time.clock
On the Windows operating system, Time.clock () returns the number of seconds that the method has been called for the first time, with an accuracy greater than 1 microseconds. You can use this function to log the time that the program executes.
import timeprint time.clock()time.sleep(2)print time.clock()time.sleep(3)print time.clock()
Time.gmtime
The function prototype is: Time.gmtime ([sec]), the optional parameter SEC represents the number of seconds since 1970-1-1. Its default value is Time.time (), which returns an object of type Time.struct_time (Struct_time is the object representing the time defined in the Times module).
import timeprint time.gmtime() print246060
Time.localtime
Time.localtime is very similar to Time.gmtime and returns a Struct_time object that can be seen as a localized version of Gmtime ().
Time.mktime
Time.mktime performs the opposite of Gmtime (), localtime (), which receives the Struct_time object as a parameter, returning 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, and its function prototype is: Time.strftime (format[, T]). The parameters format is a format string (the knowledge of the format string can be referred to: Time.strftime), and 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
Resolves a string representing time in the specified format, returning the Struct_time object. The function is prototyped as: Time.strptime (string, format), and two arguments are strings.
import timeprint time.strptime(‘201-06-23 15:30:53‘‘%Y-%m-%d %H:%M:%S‘)
These are just some of the most commonly used methods in the time module, there are many other methods such as: Time.timezone, Time.tzname ... Interested children's shoes can refer to the Python manual time module
datetime Module
A datetime module defines two constants: DateTime. Minyear and Datetime.maxyear, respectively, representing the minimum and maximum year that datetime can represent. wherein, Minyear = 1,maxyear = 9999.
The DateTime module defines the following classes:
-datetime.date: A class that represents a date. The commonly used attributes are year, month and day;
-datetime.time: A class that represents time. The commonly used properties are hour, minute, second, microsecond;
-datetime.datetime: Represents the DateTime.
-datetime.timedelta: Represents the time interval, which is the length between two points in time.
-datetime.tzinfo: Related information about the time zone. (This class is not discussed in detail here, and interested children's shoes can refer to the Python manual)
Note: These types of objects above are immutable (immutable).
Date Class
The date class represents a day. Its constructor is as follows:
class datetime.date(year, month, day)
The range of year is [Minyear, maxyear], i.e. [1, 9999];
The range of month is [1, 12];
The maximum value of day is determined by the given year, month parameter, and the leap year February has 29 days.
The date class defines some commonly used class methods and class properties to facilitate our operation:
The maximum and minimum date the-date.max and Date.min:date objects can represent;
The-date.resolution:date object represents the smallest unit of the date. This 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 timestamp;
-datetime.fromordinal (ordinal): Converts the Gregorian calendar time to a Date object; (Gregorian calendar: A calendar representation, similar to our lunar calendar, is used more in Western countries.) )
fromimportimport time print‘date.max:‘print‘date.min:‘print‘date.today():‘print‘date.fromtimestamp():‘, date.fromtimestamp(time.time())
Date-provided instance methods and properties:
-date.year, Date.month, Date.day: Year, month, day,
-date.replace (years, Month, days): Generates a new Date object, Replaces the attributes in 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, returns 0 if it is Week 2, returns 1, and so on;
-data.isoweekday (): Returns weekday, if it is Monday, returns 1, if it is Week 2, returns 2,
-date.isocalendar (): Returns a tuple of the format (year,month,day);
-date.isoformat (): Returns a string formatted as ' YYYY-MM-DD ';
- Date.strftime (FMT): Custom formatted string.
from datetime Import * now = date (2015 , 6 , 10 ) tomorrow = now.replace (day = 11 ) print , now, ', Tomorrow: ' , Tomorrowprint " timetuple (): ' , Now.timetuple () print Weekday (): ' , Now.weekday () print " Isoweekday (): ' , Now.isoweekday () print Isocalendar (): ' , Now.isocalendar () print Span class= "hljs-string" > ' Isoformat (): ' , Now.isoformat ()
Date also overloads some operations, allowing you to do some of the following on dates:
-date2 = date1 + Timedelta # date plus an interval, returns a new Date object (Timedelta will be described below, representing the time interval)
-date2 = date1-timedelta # date interval, returns a new Date object
-timedelta = date1-date2 # Two date subtraction, returns a time interval object
Date1 < Date2 # Two dates to compare
Note: When working on a date, prevent the date from exceeding the range it can represent.
fromimport11)delta = tomorrow - nowprint‘now:‘‘ tomorrow:‘, tomorrowprint‘timedelta:‘, deltaprint now + deltaprint tomorrow > now
Time class
The time class represents times, consisting of hours, minutes, seconds, and microseconds. The constructor for the time class is as follows:
class datetime.time(hour[, minute[, second[, microsecond[, tzinfo]]]])
The parameter tzinfo represents the time zone information. The range of parameters: the range of Hour is [0], the range of minute is [0], the range of second is [0, 0], the range of microsecond is [1000000].
class properties defined by the time class:
The minimum and maximum time that the-time.min, Time.max:time class can represent. where time.min = time (0, 0, 0, 0), Time.max = time (23, 59, 59, 999999);
-time.resolution: The smallest unit of time, here is 1 microseconds;
The time class provides instance methods and properties:
-time.hour, Time.minute, Time.second, Time.microsecond: Hours, minutes, seconds, microseconds;
-time.tzinfo: time zone information;
-time.replace ([hour[, minute[, second[, microsecond[, Tzinfo]]]]): Creates a new time object with the time, minutes, seconds, and microseconds specified by the parameter instead of the attributes in the original object (the original object remains unchanged);
-time.isoformat (): A string representation of the return type, such as "HH:MM:SS" format;
-time.strftime (FMT): Returns a custom formatted string.
fromimport * tm = time(71710print‘tm:‘print‘hour: %d, minute: %d, second: %d, microsecond: %d‘ 8print‘tm1:‘print‘isoformat():‘, tm.isoformat()
Like date, time can also be compared to two times objects, or subtract to return an interval object.
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 meanings of each parameter are the same as in the constructor of date and time, so be aware of the range of parameter values.
The class properties and methods defined by the DateTime class:
The minimum and maximum values that can be expressed by-datetime.min and Datetime.max:datetime;
-datetime.resolution:datetime minimum Unit;
-datetime.today (): Returns a DateTime object representing the current local time;
-datetime.now ([TZ]): Returns a DateTime object that represents the current local time, and if the parameter tz is provided, gets the local time of the time zone referred to by the TZ parameter;
-datetime.utcnow (): Returns a DateTime object for the current UTC time;
-datetime.fromtimestamp (timestamp[, TZ]): Creates a DateTime object according to the time timestamp, and the parameter TZ specifies the time zone information;
-datetime.utcfromtimestamp (timestamp): Creates a DateTime object based on the time timestamp;
-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;
fromDatetimeImport*ImportTimePrint ' Datetime.max: ', Datetime.maxPrint ' datetime.min: ', Datetime.minPrint ' datetime.resolution: ', datetime.resolutionPrint ' 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 properties provided by the DateTime class (many properties or methods already appear in date and time, refer to above):
-datetime.year, month, day, hour, minute, second, microsecond, Tzinfo:
-datetime.date (): Gets the Date object;
-datetime.time (): Gets 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 datetime equivalent to Time.ctime (Time.mktime (Dt.timetuple ()));
Datetime.strftime (format)
Like date, you can compare two DateTime objects, or subtract a time interval object, or return a new DateTime object with a DateTime plus an interval.
format string
datetime, date, and time all provide the strftime () method, which receives a format string that outputs a string representation of the DateTime.
format Characters |
meaning |
%a |
Abbreviations for the week, such as Wednesday for the web |
%A |
Full writing of the week, as in Wednesday for Wednesday |
%b |
Abbreviations for the month, such as April Apr |
%B |
Full write of the month, as in April for April |
%c |
A string representation of the DateTime. (Example: 04/07/10 10:43:39) |
%d |
The number of days in this month (the day of the week) |
%f |
microseconds (range [0,999999]) |
%H |
Hours (24-hour, [0, 23]) |
%I |
Hours (12-hour, [0, 11]) |
%j |
Number of days in the year [001,366] (the day ordinal of that year) |
%m |
Month ([01,12]) |
%M |
Minutes ([00,59]) |
%p |
AM or PM |
%s |
seconds (range = [00,61]) |
%u |
Weeks of the week in the current year), Sunday as the first day of the week |
%w |
Today in this week's number of days, the range is [0, 6],6 represents Sunday |
%W |
Week of the year (the Week of the year), 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 |
2 Number of years represented |
%Y |
4 Number of years represented |
%z |
Interval to UTC time (returns an empty string if local time) |
%Z |
Time zone name (if local time, returns an empty string) |
%% |
Percent% =% |
fromDatetimeImport*ImportTimedt = 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%s day of the week '% Dt.strftime ('%w ')Print ' Today is the first%s day of the year '% Dt.strftime ('%j ')Print ' This week is this year's%s week '% Dt.strftime ('%u ')
Python Module Learning notes--time and Datatime