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. 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.) )
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.
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.
Time class
The time class represents times, consisting of hours, minutes, seconds, and microseconds. (I'm not from Mars.) 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 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. described in detail below;
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 constructor of date, time, 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;
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 the C format string for a DateTime equivalent to Time.ctime (Time.mktime (Dt.timetuple ()));
- datetime. strftime (format)
ImportdatetimeImport Time" "Datetime.datetime.now (TZ) returns the current timestamp object for the specified time zone, without specifying a time zone object, which defaults to the local time zone (such as Beijing time)" "D= Datetime.datetime.now ()#Datetime.datetime ObjectPrint(Type (d), D) D_year= D.year#yearsD_month = D.month#MonthD_day = D.day#DayD_hour = D.hour#whenD_min = D.minute#pointsD_sec = D.second#secondsD_msec = D.microsecond#millisecondsPrint('%4d-%02d-%02d%02d:%02d:%02d.%d'%(D_year, D_month, D_day, D_hour, D_min, D_sec, d_msec)) D_today= Datetime.date.today ()#Datetime.date ObjectPrint(Type (d_today), D_today)#D_today_year = D_today.year#yearsD_today_month = D_today.month#MonthD_today_day = D_today.day#DayPrint('%04d-%02d-%02d'%(D_today_year, D_today_month, d_today_day))Print(Datetime.date (2017, 7, 25))#Create a Datetime.date objectPrint(Datetime.date.today () + Datetime.timedelta (2))#The day afterPrint(Datetime.date.today () + Datetime.timedelta (-1))#YesterdayD_time_min= Datetime.time.min#Day start TimeD_time_max = Datetime.time.max#Day End TimePrint(Type (d_time_min), D_time_min, D_time_max)Print('%02d:%02d:%02d.%d'%(D_time_max.hour, D_time_max.minute, D_time_max.second, D_time_max.microsecond))" "datetime.datetime.combine (date, time) combines a date object and a temporal object into a DateTime object" "Print(Datetime.datetime.combine (Datetime.date.today (), d_time_min))Print(Datetime.datetime.combine (Datetime.date.today (), D_time_max)) D_timedelta= Datetime.timedelta (1.00001)#Datetime.timedelta ObjectPrint(Type (D_timedelta), D_timedelta)Print(D_timedelta.total_seconds ())#the total number of seconds of the time differencePrint(d_timedelta.microseconds)#the number of milliseconds (not the total) of the time differencePrint(d_timedelta.days)#total days of the time difference (rounded)" "Relationship Transformation" "#Convert a Datetime.datetime object to a time stringD_datetime_str = D.strftime ('%y-%m-%d%h:%m:%s')Print(D_DATETIME_STR)" "%a Week's shorthand. As Wednesday for Web%a week's full write. For example, Wednesday is abbreviated for WEDNESDAY%B month. such as April for the full write of Apr%b month. As in April, april%c: A string representation of the DateTime. (Example: 04/07/10 10:43:39)%d: Days in this month (the day of the week)%f: microseconds (range [0,999999])%H: Hours (24-hour, [0,])%I: Hours (12-hour, [0, one])%j: 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 (range = [00,61], why not [00, 59], refer to Python manual ~_~)%u: Weeks in the current year of the Week of the year, Sunday as the first day of the week%w: Today in this week, the number of days, the range is [0, 6],6 represents Sunday%w: Week in the Year of the week (is the first week of the year), Monday as the day of the week%x: date string (such as: 04/07/10)%x: A time string (such as: 10:43:39)%y:2 A number representing the year%y:4 the year%Z: Interval from UTC (If local time, returns an empty string)%Z: Time zone name (returns an empty string if local time) percent:%" "#converts a time string to a Datetime.datetime object by a specified date format stringD_DATETIME_STRP = Datetime.datetime.strptime (D_datetime_str,"%y-%m-%d%h:%m:%s")Print(Type (D_DATETIME_STRP), D_DATETIME_STRP)#Convert a Datetime.datetime object to a time tupleD_timetuple =d.timetuple ()Print(Type (d_timetuple), d_timetuple)#Convert a Datetime.datetime object to a Datetime.date objectD_now_date =d.date ()Print(Type (d_now_date), d_now_date)#converts a Datetime.datetime object to a timestamp floating point number (seconds from 1970.1.1)D_timestamp =time.mktime (d_timetuple)Print(Type (d_timestamp), D_timestamp)#Convert a timestamp floating-point number to a Datetime.datetime objectD_fromtimestamp =Datetime.datetime.fromtimestamp (D_timestamp)Print(Type (d_fromtimestamp), D_fromtimestamp)
Python module-datetime