Time and datetime modules in Python are modules in the temporal context
One, Time module
There are three types of time-performance formats in the Times module:
1, timestamp: Timestamp, time stamp represents the offset in seconds from January 1, 1970 00:00:00
2, Struct_time: Time tuple, a total of nine element groups.
3. Format time: Formatting times, formatted structure makes time more readable. Includes custom formats and fixed formats.
1. Time Format conversion diagram:
2. The main time generation method and the time format conversion method instance:
Generate Timestamp (timestamp)
1 >>>
2 >>> import time
3 >>> time.time ()
4 1491631287.1797802
5 >>> #Generate timestamp by struct_time
6 >>> time.mktime (time.localtime ())
7 1491631461.0 #Always followed by a decimal, 0?
8 >>>
Generate Struct_time (Time tuple)
1 >>> #directly generate time tuples
2 >>> time.localtime ()
3 time.struct_time (tm_year = 2017, tm_mon = 4, tm_mday = 8, tm_hour = 14, tm_min = 7, tm_sec = 20, tm_wday = 5, tm_yday = 98, tm_isdst = 0)
4 >>> #Convert timestamp to time tuple
5 >>> time.localtime (time.time ())
6 time.struct_time (tm_year = 2017, tm_mon = 4, tm_mday = 8, tm_hour = 14, tm_min = 8, tm_sec = 5, tm_wday = 5, tm_yday = 98, tm_isdst = 0)
7 >>> #Replace localtime () with gmtime () for Greenwich Mean Time
8 >>>
9 >>> #Convert formatted time to time tuple
10 >>> time.strptime (‘2017-4-8 14:12:12’, ‘% Y-% m-% d% X’)
11 time.struct_time (tm_year = 2017, tm_mon = 4, tm_mday = 8, tm_hour = 14, tm_min = 12, tm_sec = 12, tm_wday = 5, tm_yday = 98, tm_isdst = -1)
12 >>> time.strptime (‘2017-4-8’, ’% Y-% m-% d’)
13 time.struct_time (tm_year = 2017, tm_mon = 4, tm_mday = 8, tm_hour = 0, tm_min = 0, tm_sec = 0, tm_wday = 5, tm_yday = 98, tm_isdst = -1)
14 >>>
Property value
Tm_year (year) such as 2017
Tm_mon (month) 1-12
Tm_mday (Sunday) 1-31
Tm_hour (hours) 0-23
Tm_min (minutes) 0-59
Tm_sec (seconds) 0-61
Tm_wday (weekday) 0-6 (0 means Sunday)
Tm_yday (day of the year) 1-366
Tm_isdst (Whether it is daylight saving time)
Generate Format_time (format time)
1 >>>
2 >>> #Generate format_time directly
3 >>> time.strftime (‘% Y-% m-% d% X’)
4 ‘2017-04-08 14:16:11’
5 >>>
6 >>> #Convert struct_time to format_time
7 >>> time.strftime (‘% Y-% m-% d% X’, time.localtime ())
8 ‘2017-04-08 14:17:30’
9 >>>
% Y Year with century as a decimal number.
% M Month as a decimal number [01,12].
% D Day of the month as a decimal number [01,31].
% H at Hour (24-hour clock) as a decimal number [00,23].
% M points Minute as a decimal number [00,59].
% S seconds Second as a decimal number [00,61].
% Z Time zone offset from UTC.
% A Weekday abbreviation (English) Locale ‘s abbreviated weekday name.
% A Sunday full name (English Sunday) Locale ’s full weekday name.
% B Month abbreviation (English Apr) Locale ’s abbreviated month name.
% B Full month name (English April) Locale ’s full month name.
% C Locale ‘s appropriate date and time representation.
% I Hour (12-hour clock) as a decimal number [01,12].
% P AM / PM Locale ‘s equivalent of either AM or PM.
% X local corresponding time
% X local corresponding date
Generate a fixed-format time representation format
1 >>> time.asctime()
2 ‘Sat Apr 8 14:20:04 2017‘
3 >>>
4 >>> time.ctime()
5 ‘Sat Apr 8 14:20:09 2017‘
6 >>>
7 >>> time.asctime(time.localtime())
8 ‘Sat Apr 8 14:20:27 2017‘
9 >>>
10 >>> time.ctime(time.time())
11 ‘Sat Apr 8 14:20:44 2017‘
3. Time plus minus
1 >>>
2 >>> #timestamp addition and subtraction are in seconds
3 >>> import time
4 >>> t1 = time.time ()
5 >>> t2 = t1 + 10
6 >>> t1
7 1491634614.3497803
8 >>> t2
9 1491634624.3497803
10 >>>
Second, the DateTime module
The Datatime module encapsulates the time module, providing more interfaces and providing classes that are: Date,time,datetime,timedelta,tzinfo.
1. Date class
Datetime.date (year, month, day)
Static Methods and fields
date.max, date.min: the maximum and minimum dates that a date object can represent;
date.resolution: The smallest unit of a date object representing a date. Here is the day.
date.today (): returns a date object representing the current local date;
date.fromtimestamp (timestamp): returns a date object according to the given time;
1 >>> import datetime
2 >>> datetime.date.max
3 datetime.date (9999, 12, 31)
4 >>> datetime.date.min
5 datetime.date (1, 1, 1)
6 >>> datetime.date.resolution
7 datetime.timedelta (1)
8 >>> datetime.date.today ()
9 datetime.date (2017, 4, 8)
10 >>> datetime.date.fromtimestamp (time.time ())
11 datetime.date (2017, 4, 8)
12 >>>
Methods and properties
d1 = date (2017,4,8) #date object (year, month, day cannot start with 0 (2017,04,08) error)
>>> d1 = datetime.date (2017,4,8)
>>> d1
datetime.date (2017, 4, 8)
>>> d1.year
2017
>>> d1.month
4
>>> d1.day
8
>>>
d1.replace (year, month, day): generate a new date object, replacing the attributes in the original object with the year, month, and day specified by the parameters. (The original object remains unchanged)
>>> d2 = d1.replace (2017,3,20)
>>> d1
datetime.date (2017, 4, 8)
>>> d2
datetime.date (2017, 3, 20)
>>>
d1.timetuple (): returns the time.struct_time object corresponding to the date;
>>> d1.timetuple ()
time.struct_time (tm_year = 2017, tm_mon = 4, tm_mday = 8, tm_hour = 0, tm_min = 0, tm_sec = 0, tm_wday = 5, tm_yday = 98, tm_isdst = -1)
>>>
d1.weekday (): returns weekday, if it is Monday, it returns 0; if it is week 2, it returns 1, and so on;
>>> d1.weekday ()
5 #Sat
>>>
d1.isoweekday (): returns weekday, if it is Monday, it returns 1; if it is week 2, it returns 2, and so on;
>>> d1.isoweekday ()
6 #Saturday weekday mirror?
>>>
d1.isocalendar (): returns a tuple in the format (year, sum_week, day);
>>> d1
datetime.date (2017, 4, 8)
>>> d1.isocalendar ()
(2017, 14, 6) #The first is 2017, 14 is currently the 14th week of the year 6 means 6 days have passed since the end of the 14th week (currently 15 weeks)
>>>
d1.isoformat (): Returns a string with a format such as 'YYYY-MM-DD';
>>> d1.isoformat ()
‘2017-04-08’
>>>
d1.strftime (fmt): Same as the time module format.
>>> d1.strftime (‘% Y-% m-% d’)
‘2017-04-08’
>>>
.
2. Time Class
Datetime.time (Hour[, Minute[, second[, microsecond[, Tzinfo] ] ]
Static Methods and fields
time.min, time.max: the minimum and maximum time that the time class can represent
>>> import datetime
>>> datetime.time.min
datetime.time (0, 0)
>>> datetime.time.max
datetime.time (23, 59, 59, 999999)
>>>
time.resolution: the smallest unit of time, here is 1 microsecond;
>>> datetime.time.resolution
datetime.timedelta (0, 0, 1) #seconds, milliseconds, microseconds
>>>
Methods and properties
t1 = datetime.time (10,23,15) #time object hours, minutes, seconds ...
t1.hour, t1.minute, t1.second, t1.microsecond: hours, minutes, seconds, microseconds;
>>> t = datetime.time (15,30,20)
>>> t
datetime.time (15, 30, 20)
>>> t.hour
15
>>> t.minute
30
>>> t.second
20
>>> t.microsecond
0
>>>
t1.tzinfo: time zone information;
t1.replace ([hour [, minute [, second [, microsecond [, tzinfo]]]]]): create a new time object, replacing the original object with the hour, minute, second, and microsecond specified by the parameters Attributes
(The original object remains unchanged);
t1.isoformat (): Returns a string representation in the format "HH: MM: SS";
t1.strftime (fmt): same as the format in the time module;
3, datetime class
datetime is equivalent to the combination of date and time.
datetime.datetime (year, month, day [, hour [, minute [, second [, microsecond [, tzinfo]]]]])
Static methods and fields
datetime.today (): returns a datetime object representing the current local time;
datetime.now ([tz]): returns a datetime object representing the current local time. If the parameter tz is provided, the local time in the time zone indicated by the tz parameter is obtained;
datetime.utcnow (): Returns a datetime object for the current UTC time; #Greenwich Mean Time
datetime.fromtimestamp (timestamp [, tz]): create a datetime object according to the time, the parameter tz specifies the time zone information
datetime.utcfromtimestamp (timestamp): create a datetime object based on the time;
datetime.combine (date, time): create a datetime object based on date and time;
datetime.strptime (date_string, format): convert the format string into a datetime object;
Methods and properties
dt = datetime.now () # datetime object
dt.year, month, day, hour, minute, second, microsecond, tzinfo:
dt.date (): Get the date object;
dt.time (): Get the time object;
dt. replace ([year [, month [, day [, hour [, minute [, second [, microsecond [, tzinfo]]]]]]]]):
dt. timetuple ()
dt. utctimetuple ()
dt. toordinal ()
dt. weekday ()
dt. isocalendar ()
dt. isoformat ([sep])
dt. ctime (): returns a date format C string, equivalent to time.ctime (time.mktime (dt.timetuple ()));
dt. strftime (format)
4.timedelta class, time addition and subtraction
Using timedelta, you can easily calculate days, hours, minutes, seconds, milliseconds, and delicate time on the date. If you want to calculate the month, you need another method.
1 >>> import datetime
2 >>> d = datetime.datetime.now ()
3 >>> d
4 datetime.datetime (2017, 4, 8, 15, 42, 1, 656144) 8 >>> d1 = d + datetime.timedelta (days = -1) #yesterday
9 >>> d1
10 datetime.datetime (2017, 4, 7, 15, 42, 1, 656144)
11 >>> d2 = d-datetime.timedelta (days = 1) #yesterday
12 >>> d2
13 datetime.datetime (2017, 4, 7, 15, 42, 1, 656144)
14 >>> d3 = d + datetime.timedelta (days = 1) #tomorrow
15 >>> d3
16 datetime.datetime (2017, 4, 9, 15, 42, 1, 656144)
17 >>>
5, tzinfo time zone class
#! / usr / bin / python
# coding = utf-8
from datetime import datetime, tzinfo, timedelta
"" "
tzinfo is a class about time zone information
tzinfo is an abstract class, so it cannot be instantiated directly
"" "
class UTC (tzinfo):
"" "UTC" ""
def __init __ (self, offset = 0):
self._offset = offset
def utcoffset (self, dt):
return timedelta (hours = self._offset)
def tzname (self, dt):
return "UTC +% s"% self._offset
def dst (self, dt):
return timedelta (hours = self._offset)
#Beijing time
beijing = datetime (2011,11,11,0,0,0, tzinfo = UTC (8))
print "beijing time:", beijing
#Bangkok Time
bangkok = datetime (2011,11,11,0,0,0, tzinfo = UTC (7))
print "bangkok time", bangkok
#Beijing Time to Bangkok Time
print "beijing-time to bangkok-time:", beijing.astimezone (UTC (7))
#The time zone is also considered when calculating the time difference
timespan = beijing-bangkok
print "Time difference:", timespan
#Output ====================
# beijing time: 2011-11-11 00: 00: 00 + 08: 00
# bangkok time 2011-11-11 00: 00: 00 + 07: 00
# beijing-time to bangkok-time: 2011-11-10 23: 00: 00 + 07: 00
# Time difference: -1 day, 23:00:00
Common modules-time and dattime modules-stack overflow