The Python time and date operations need to use the datetime and Timing standard library modules.
One, Time module
1.time module represents the way of time
① time Stamp
② formatted time string
③ in the form of an array (struct_time), a total of nine elements year (four digits, e.g. 1998) month (1-12) Day (1-31) hours (0-23) minutes (0-59) Seconds (0-59) weekday (0-6, Monday is 0) Julian Day (day in the year, 1-366) DST (Daylight Savings Time) flag ( -1, 0 or 1 Whether it is daylight saving time
2. Common Functions
①asctime ([tuple])-> string
Converts a struct_time (the default is then time) to a string.
>>> time.asctime ()
' Sun June 11:10:39 2016 '
>>> import time
>>> thistime = ' 2016-07-31 12:12:12 "
>>> timetuple = Time.strptime (Thistime,"%y-%m-%d%h:%m:%s ")
>>> Time.asctime (timetuple)
' Sun June 31 12:12:12 2016 '
②ctime (seconds)-> string
Converts a timestamp (the default current time) into a time string.
>>> time.ctime ()
' Sun June 11:11:33 2016 '
>>> time.ctime (1469938332)
' Sun June 31 12:12:12 2016 '
③gmtime ([seconds])-> (tm_year, Tm_mon , Tm_day, Tm_hour, Tm_min,tm_sec, Tm_wday, Tm_yday, TM_ISDST)
Converts a timestamp to the struct_time of a UTC time zone (0 o'clock) and, if the seconds parameter is not entered, the current time as the conversion standard.
>>> time.gmtime ()
time.struct_time (tm_year=2016, tm_mon=7, tm_mday=31, tm_hour=3, tm_min=15, tm_sec=35, Tm_wday=6, tm_yday=213, tm_isdst=0)
>>> time.gmtime (1469938332)
time.struct_time (tm_year=2016, TM _mon=7, tm_mday=31, tm_hour=4, tm_min=12, tm_sec=12, tm_wday=6, tm_yday=213, tm_isdst=0)
④localtime ([seconds])-> (TM_YEAR,TM_MON,TM_DAY,TM_HOUR,TM_MIN,TM_SEC,TM_WDAY,TM_YDAY,TM_ISDST)
Converts a timestamp to the struct_time of a current time zone, and if the seconds parameter is not entered, the current period is the conversion standard.
>>> time.localtime ()
time.struct_time (tm_year=2016, tm_mon=7, tm_mday=31, tm_hour=11, tm_min=17, tm_sec =17, Tm_wday=6, tm_yday=213, tm_isdst=0)
>>> time.localtime (1469938332)
time.struct_time (tm_year= 2016, tm_mon=7, tm_mday=31, tm_hour=12, tm_min=12, tm_sec=12, tm_wday=6, tm_yday=213, tm_isdst=0)
⑤mktime (tuple)-> floating point number
Converts a struct_time to a timestamp.
>>> Import Time
>>> thistime = "2016-07-31 12:12:12"
>>> timetuple = Time.strptime ( Thistime, "%y-%m-%d%h:%m:%s")
>>> time.mktime (timetuple)
1469938332.0
⑥strftime (format[, tuple])-> string
Outputs the specified struct_time (the default current time), according to the specified formatted string.
>>> time.strftime ("%y-%m-%d%h:%m:%s")
' 2016-07-31 11:20:41 '
>>> import time
>> > thistime = "2016-07-31 12:12:12"
>>> timetuple = Time.strptime (Thistime, "%y-%m-%d%h:%m:%s")
>>> time.strftime ("%y-%m-%d%h:%m:%s", timetuple)
' 2016-07-31 12:12:12 '
⑦strptime (string, format)-> struct_time
Converts the time string into an array of times based on the specified format character.
>>> Import Time
>>> thistime = "2016-07-31 12:12:12"
>>> timetuple = Time.strptime ( Thistime, "%y-%m-%d%h:%m:%s")
>>> print timetuple
time.struct_time (tm_year=2016, tm_mon=7, tm_ Mday=31, tm_hour=12, tm_min=12, tm_sec=12, tm_wday=6, tm_yday=213, Tm_isdst=-1)
⑧time ()-> floating point number
Returns the time stamp for the current time.
>>> time.time ()
1469935566.776
Second, the datetime module
the constant datetime in 1.datetime . Minyear, which represents the minimum year that datetime can represent, Minyear = 1. Datetime. Maxyear, which represents the maximum year that datetime can represent, Maxyear = 9999.
class Datetime.date in 2.datetime : A class that represents a date. The commonly used attributes are year, month, day, Datetime.time: The class that represents the time. Commonly used properties are hour, minute, second, microsecond; Datetime.datetime: Represents DateTime. Datetime.timedelta: Represents the time interval, that is, the length between two points in time. Datetime.tzinfo: Related information about the time zone.
3.date class
The date class represents a date that consists of a year, a month, and a day.
① class methods and class attributes
The date class defines some of the common class methods and class attributes that allow us to manipulate: the maximum and minimum dates the Date.max, date.min:date objects can represent, and the Date.resolution:date object represents the smallest unit of 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 a given timestamp; Datetime.fromordinal ( Ordinal): Converts the Gregorian calendar time to a Date object; (Gregorian calendar: A method of calendars, similar to the Chinese lunar calendar, Western countries use more, this is not discussed in detail.) )
② instance methods and properties
Instance methods and properties provided by Date: Date.year, Date.month, Date.day: Year, month, day, Date.replace (years, Month,day): Generate a new Date object, with parameters specified by the year, month, Day instead of the attributes in the original object. (The original object remains unchanged) 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 (): Return to weekday, if it is Monday, return 0; If it is the Week 2, return 1, and so on; Data.isoweekday (): Return to weekday, if it is Monday, return 1; if it is 2, return 2, and so on; Date.isocalendar (): Returns a tuple of a format such as (Year,month,day); Date.isoformat (): Returns a string formatted as ' YYYY-MM-DD '; Date.strftime (FMT) : a custom format string. Explained in detail below.
other operations supported by ③date date2 = date1 + Timedelta #日期加上一个间隔, returns a new Date object) Date2 = Date1-timedelta #日期隔去间隔, returns a new Date object Timedel Ta = Date1-date2 #两个日期相减, returns a time interval object Date1 < Date2 #两个日期进行比较
4.Time class
Time classes represent times, which consist of hours, minutes, seconds, and microseconds.
The ①time class- defined Class Property Time.min, the minimum and maximum time that the Time.max:time class can represent. Among them, Time.min = time (0, 0, 0, 0), Time.max = Times (n, S, 999999); Time.resolution: the smallest unit of the hour, here is 1 microseconds;
②time class provides instance methods and properties Time.hour, Time.minute, Time.second, Time.microsecond: Time, minutes, seconds, microseconds; Time.tzinfo: time zone information; Time.replace ([hour[, minute[, second[, microsecond[, Tzinfo]]]: Creates a new time object that replaces the attributes in the original object with the time, minutes, seconds, and microseconds specified by the parameter (the original object remains unchanged); Time.isoformat (): Returns a string representation of the form, such as "HH:MM:SS", Time.strftime (FMT): Returns a custom format string. described in detail below;
As with date, two time objects can be compared or subtracted to return an interval object.
The
5.datetime class
DateTime is a combination of date and time, including all information about date and time. The
①datetime class-defined class properties and methods Datetime.min, Datetime.max:datetime can represent the minimum and maximum values; 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 a 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 based on the timestamp, parameter TZ Specifies the time zone information; Datetime.utcfromtimestamp (timestamp) : Create a DateTime object based on the timestamp; Datetime.combine (date, time): Creates a DateTime object based on date and time; Datetime.strptime (date_string, Format): Converts a formatted string to a DateTime object;
The
②datetime class provides instance methods and properties datetime.year, month, day, hour, minute, second, microsecond, Tzinfo: Years, months, days, times, Minutes, seconds, milliseconds, time zone; Datetime.date (): Gets the Date object. Datetime.time (): Gets the time object. Datetime. Replace ([year[, month[, day[, hour[, minute[, second[, microsecond[, Tzinfo]]]: Returns a new datet that replaces the specified date-time field The IME object. Datetime.timetuple (): Returns a time element, equivalent to Time.localtime (). Datetime. Utctimetuple (): Returns the UTC time Tuple object, equivalent to Time.localtime (). Datetime. Toordinal (): Returns the Gregorian Calendar date corresponding to the date. Datetime. Weekday (): returns 0 ~ 6 for the day of the week (Monday is 0, and so on). Datetime. Isocalendar (): Returns a ternary format (year, month, day). Datetime. Isoformat ([Sep]): Returns an ISO 8601 format date string, such as a string of "Yyyy-mm-dd". Datetime. CTime (): Returns a date-time C format string that is equivalent to Time.ctime (Time.mktime (Dt.timetuple ()); DateTime. Strftime (format): Returns a custom formatted string representing the date.
Like date, you can compare two DateTime objects, or subtract a time interval object, or a date time plus an interval to return a new DateTime object.
6.timedelta and Tzinfo class
①timedelta class
The Datetime.timedelta object represents the time difference between two times, and two date or DateTime objects can return a Timedelta object when they are subtracted.
The Timedelta contains the data days, seconds, and microseconds, representing the day, seconds, and microseconds, including the method Total_seconds (), which represents the total number of seconds in the interval.
②tzinfo class
Tzinfo: Related information about the time zone.
Iii. Common Date-time operations
1. Convert a date in a string format to a timestamp
Method: Convert it to a time tuple and then to a timestamp.
>>> Import Time
>>> thistime = "2016-07-31 12:12:12"
>>> timetuple = Time.strptime ( Thistime, "%y-%m-%d%h:%m:%s")
>>> timeStamp = Int (time.mktime))
>>> Print TimeStamp
1469938332
2. Convert a timestamp to a date in the specified format
Method One
>>> Import Time
>>> timeStamp = 1469938332
>>> timetuple = Time.localtime (timeStamp )
>>> othertime = Time.strftime ("%y-%m-%d%h:%m:%s", timetuple)
>>> print Othertime
2016-07-31 12:12:12
Method Two
>>> import datetime
>>> timeStamp = 1469938332
>>> dt= Datetime.datetime.utcfromtimestamp (timeStamp)
>>> othertime = Dt.strftime ("%y-%m-%d%h:%m:%s")
>>> print othertime
2016-07-31 04:12:12
3. Change date format
Method: Converts to a time tuple and then to another format.
>>> Import Time
>>> thistime = "2016-07-31 12:12:12"
>>>timetuple = Time.strptime (Thistime, "%y-%m-%d%h:%m:%s")
>>>othertime = Time.strftime ("%y/%m/%d%h:%m:%s", timetuple)
>>> print Othertime
2016/07 /31 12:12:12
4. Convert the current time to the specified date format
Method One:
>>> Import Time
>>> nowstamp = Int (Time.time ())
>>> timetuple = Time.localtime ( Nowstamp)
>>> othertime = Time.strftime ("%y-%m-%d%h:%m:%s", timetuple)
>>> print Othertime
2016-07-31 10:19:47
Method Two:
>>> import datetime
>>> now = Datetime.datetime.now ()
>>> othertime = Now.strftime ( "%y-%m-%d%h:%m:%s")
>>> print othertime
2016-07-31 10:21:45
5, get today, yesterday and tomorrow's date
>>> import datetime
>>> today = Datetime.date.today ()
>>> yesterday =- Datetime.timedelta (Days=1)
>>> tomorrow = Today + Datetime.timedelta (days=1)
>>> Print Yesterday:%s, today:%s, tomorrow:%s% (Yesterday, today, Tomorrow)
yesterday: 2016-07-30, Day: 2016-07-31, Tomorrow: 2016-08-01
6. Calculate the time of the first 1 days and the following day
>>> import datetime
>>> Dtonedayago = (Datetime.datetime.now ()-Datetime.timedelta (days = 1)). Strftime ("%y-%m-%d%h:%m:%s")
>>> dtonedayafter = (Datetime.datetime.now () + Datetime.timedelta (days = 1) ). Strftime ("%y-%m-%d%h:%m:%s")
>>> print dtonedayago,dtonedayafter
2016-07-30 10:39:54 2016-08-01 10:40:14
7, get the current time
(1) Use time module
>>> Import Time
>>> currenttime = Time.strftime ("%h:%m:%s")
>>> print CurrentTime
10:44:30
(2) using the DateTime module
>>> import datetime
>>> now = Datetime.datetime.now ()
>>> currenttime=str ( Now.hour) + ":" +str (Now.minute) + ":" +str (now.second)
>>> print currenttime
10:52:18
Four, date and time formatting parameters %a Day of the week%a the full name of the day of the week%b monthly number of the month of the full name of the "%c" Day of the date of the two-digit%d decimal notation Month/day/year%e in two-character fields, the number of%F-month-day%g years of the month in decimal notation, using the%g year of the week, and the%h of a 24-hour system based on the annual%h abbreviated month%I The 12-hour%j decimal representation of the number of days of the year%m decimal notation for the month%m 10 o'clock,%n New line character%p local AM or PM equivalent display%r 12 hours%r display hours and minutes: hh:mm%s Decimal seconds%t horizontal tab% T Show minute seconds: Hh:mm:ss%u the first day of the week, Monday is the number one (value from 0 to 6, Monday to 0%u the first few weeks of the year, the Sunday is the number one day (value from 0 to 0)%V the number of weeks of the year, using the week-old%w decimal notation for the week (values from 0 to 6, Sunday to) %w the first few weeks of the year, Monday as the first day (value from 0 to)%x Standard Time series of the date string%x%y the decimal year with a century (value from 0 to)%y The 10 year of the century part%z,%z the time zone name, or null if the time zone name cannot be obtained. Percent percent%