Python provides several built-in modules for manipulating date times, like Calendar,time,datetime. Time module I have described in the previous article, it provides the interface and C standard library time.h basically consistent. The interface of the DateTime module is more intuitive and easier to invoke than the time module.
1. DateTime contains three classes of date, Time,datetime
function Datetime.combine (date,time) can get Dateime,datetime.date (), Datetime.time () can get date and time
2. Conversion of datetime time to String
Today we'll talk about the datetime module.
1. 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.
2. 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.
Note: These types of objects above are immutable (immutable).
Here is a detailed description of how these classes are used.
First, Date class
The date class represents a day. The date is made up of the year, Month and day (the Earth knows ~ ~). The constructor for the date class is as follows:
Class Datetime.date (year, Month, day): The meaning of the parameters is not much to explain, but there are a few points to note:
- The range of year is [Minyear, maxyear], i.e. [1, 9999];
- The range of month is [1, 12]. (The month is starting from 1, not ~_~ starting from 0);
- The maximum value of day is determined by the given year, month parameter. For example 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 Chinese lunar calendar, the western countries use more, here is not discussed in detail.) )
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
From datetime import * Import time
The instance methods and properties provided by date:
- Date.year, Date.month, Date.day: Year, month, day;
- Date.replace (year, Month, day): Generates a new Date object, substituting the attributes in the original object with the years, months, and days specified by the parameter. (The original object remains unchanged)
- Date.timetuple (): Returns the Time.struct_time object corresponding to the date;
- Date.toordinal (): Returns the date corresponding to the Gregorian calendar 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, and so on;
- Date.isocalendar (): Returns a tuple with a format such as (Year,month,day);
- Date.isoformat (): Returns a string formatted as ' YYYY-MM-DD ';
- Date.strftime (FMT): Custom formatted string. Explained in detail below.
Examples of Use:
now = Date (in, tomorrow) = now.replace (day =) 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 (): (4, 6, 0, 0, 0, 1,, 1) # Weekday (): 1 # Isowee Kday (): 2 # Isocalendar (): (+, 2) # Isoformat (): 2010-04-06
now = Date (in, tomorrow) = now.replace (day =) 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 ()
Date also overloads some operations, which allow us to do some of the following with 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.
Examples of Use:
now = Date.today () tomorrow = now.replace (day = 7) Delta = tomorrow-now Print ' Today: ', now, ' Tomorrow: ', tomorrow Print ' Timedelta: ', Delta print now + Delta print tomorrow > Now # # #----Results---- # now:2010-04-06 to morrow:2010-04-07 # timedelta:1 Day, 0:00:00 # 2010-04-07 # True
now = Date.today () tomorrow = now.replace (day = 7) Delta = tomorrow-now print ' Today: ', now, ' Tomorrow: ', tomorrow Print ' Timedelta: ', Delta print now + Delta Print tomorrow > now
Second, 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 meaning of each parameter is not explained, note here the parameter tzinfo, which represents the time zone information. Note the range of values for each parameter: The range of Hour is [0], the range of minute is [0], the range of second is [0, 0], and 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. wherein, 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, replaces the attributes in the original object with the time, minute, second, and microsecond specified by the parameter (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. described in detail below;
Examples of Use:
From datetime import * tm = time (at $ ten) print ' TM: ', TM print ' hour:%d, minute:%d, second:%d, microsec Ond:%d ' \ % (Tm.hour, Tm.minute, Tm.second, tm.microsecond) TM1 = tm.replace (hour =) print ' TM1: ', TM1 print ' Isoformat (): ', Tm.isoformat () # #----Results---- # tm:23:46:10 # hour:23, minute:46, second:10, Micro second:0 # Tm1:20:46:10
From datetime import * tm = time (at $ ten) print ' TM: ', TM print ' hour:%d, minute:%d, second:%d, microsecond:%d ' \
% (Tm.hour, Tm.minute, Tm.second, tm.microsecond) TM1 = tm.replace (hour =) print ' TM1: ', TM1 print ' Isoformat (): ', Tm.isoformat ()
Like date, you can also compare two time objects, or subtract to return an interval object. Examples are not available here.
Third, 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 with date, T As in the constructor of the IME, 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;
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 ()) #----Results---- # datetime.max:9999-12-31 23:59:59.999999 # datetime.min:0001-01-01 00:00:00 # datetime.resolution: 0:00:00.000001 # Today (): 2010-04-07 09:48:16.234000 # Now (): 2010-04-07 09:48:16.234000 # utcnow (): 2010-04-07 01:48:16.234000 # China at +8 time, 8 # Fromtimestamp (tmstmp): 2010-04-07 09:48:16.234000 # Utcfromtimestamp (tmstmp): 2010-04-07 01:48:16.234000
From datetime import * Import time print ' Datetime.max: ', Datetime.max print ' datetime.min: ', datetime.min print ' date Time.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 properties provided by the DateTime class (many properties or methods have already appeared in date and time, there is a similar meaning here, only the names of these methods are listed, the meaning is no longer described individually, you can refer to the date and time class explained 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. Here do not provide a detailed example, the spectator himself try it ~ ~
Iv. converting to a string
datetime, date, and time all provide the strftime () method, which receives a format string that outputs a string representation of the DateTime. The table below is drawn from the Python manual, and I have made a simple translation (a little bit of translation).
Format characters and meanings
%a Week's shorthand. As Wednesday for web
%A week's full write. As in Wednesday for Wednesday
Abbreviated%B month. If April is Apr
Full write of%b month. As in April for April
%c: string representation of DateTime. (Example: 04/07/10 10:43:39)
%d: The number of days in the 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 of the current year)
%m: Month ([01,12])
%M: Minutes ([00,59])
%p:am or PM
%s: seconds (range = [00,61], why not [00, 59], refer to Python manual ~_~)
%u: Week in the Year of the Week of the year), Sunday as the first day of the week
%w: Today in this week's 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 the year represented by a number
%y:4 the year represented by a number
%z: Interval with UTC time (if local time, returns an empty string)
%Z: Time zone name (if local time, returns an empty string)
Percent:%
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.s Trftime ('%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 this week's%s days '% dt.strftime ('%w ') print ' Today is this year's%s day '% dt.strftime ('%j ') print ' This week is this year's%s week '% Dt.strfti Me ('%u ') # #----result---- # (%y-%m-%d%h:%m:%s%f): 2010-04-07 10:52:18 937000 # (%y-%m-%d%h:%m:%s%p): 10-04-07 10:52:18 AM #%a:wed #%a:wednesday #%b:apr #%b:april # date Time%C:04/07/10 10:52:18< c20/># date%X:04/07/10 # time%x:10:52:18 # today is the 3rd day of the Week # today is the No. 097 Day of the year # this week is the 14th week of this year
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 this week's%s days '% dt.strftime ('%w ') print ' Today is this year's%s days '% d T.strftime ('%j ') print ' This week is this year's%s week '% dt.strftime ('%u ') # #----Results----# (%y-%m-%d%h:%m:%s%f): 2010-04-07 10:52:1 8 937000 # (%y-%m-%d%h:%m:%s%p): 10-04-07 10:52:18 AM #%a:wed #%a:wednesday #%b:apr #%b:april # Date Time%C:04/07/10 10:52:18 # date%X:04/07/10 # time%x:10:52:18 # today is the 3rd day of the Week # today is the No. 097 Day of the year
Python's time,datetime,string conversion
#把datetime转成字符串 def datetime_tostring (DT): return Dt.strftime ("%y-%m-%d-%h") #把字符串转成datetime def string_ ToDateTime (String): return Datetime.strptime (String, "%y-%m-%d-%h") #把字符串转成时间戳形式 def string_totimestamp ( Strtime): return Time.mktime (String_todatetime (strtime). Timetuple ()) #把时间戳转成字符串形式 def timestamp_tostring ( Stamp): return Time.strftime ("%y-%m-%d-%h", Tiem.localtime (stamp)) #把datetime类型转外时间戳形式 def datetime_ Totimestamp (Datetim):
The above is a detailed description of the DateTime module in the Python time module, hoping to help you learn.