python有两个和时间相关的模块,datetime和time
datetime
datetime模块下有四个类
- date 日期相关的
- time 时间相关的
- datetime date和time两者的功能
- timedelta 时间差
date
查看和设置日期
>>> d = datetime.date.today()
>>> d
datetime.date(2017, 4, 30)
>>> d.year, d.month, d.day # 取年、月、日
(2017, 4, 30)
>>> d.weekday() # 星期几,从0开始算
6
>>> d.isoweekday() # 星期几,从1开始算
7
>>> datetime.date(2017, 4, 17) # 设置日期
datetime.date(2017, 4, 17)
time
构造时间
Help on class time in module datetime: class time(builtins.object)
| time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object
|
| All arguments are optional. tzinfo may be None, or an instance of
| a tzinfo subclass. The remaining arguments may be ints.
|
| Methods defined here:
|
| __eq__(self, value, /)
| Return self==value.
|
| __format__(...)
| Formats self with strftime.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __reduce__(...)
| __reduce__() -> (cls, state)
|
| __reduce_ex__(...)
| __reduce_ex__(proto) -> (cls, state)
|
| __repr__(self, /)
| Return repr(self).
|
| __str__(self, /)
| Return str(self).
|
| dst(...)
| Return self.tzinfo.dst(self).
|
| isoformat(...)
| Return string in ISO 8601 format, [HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].
|
| timespec specifies what components of the time to include.
|
| replace(...)
| Return time with new specified fields.
|
| strftime(...)
| format -> strftime() style string.
|
| tzname(...)
| Return self.tzinfo.tzname(self).
|
| utcoffset(...)
| Return self.tzinfo.utcoffset(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| fold
|
| hour
|
| microsecond
|
| minute
|
| second
|
| tzinfo
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| max = datetime.time(23, 59, 59, 999999)
|
| min = datetime.time(0, 0)
|
| resolution = datetime.timedelta(0, 0, 1) [Finished in 0.2s]
time
>>> datetime.time(15, 30, 22)
datetime.time(15, 30, 22)
>>> date = datetime.time(15, 30, 22) # 时分秒
>>> date.hour, date.minute, date.second
(15, 30, 22)
>>> date.second
22
datetime
datetime是date和time两者功能的结合
class datetime(date)
| datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
|
| The year, month and day arguments are required. tzinfo may be None, or an
| instance of a tzinfo subclass. The remaining arguments may be ints.
|
| Method resolution order:
| datetime
| date
| builtins.object
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __radd__(self, value, /)
| Return value+self.
|
| __reduce__(...)
| __reduce__() -> (cls, state)
|
| __reduce_ex__(...)
| __reduce_ex__(proto) -> (cls, state)
|
| __repr__(self, /)
| Return repr(self).
|
| __rsub__(self, value, /)
| Return value-self.
|
| __str__(self, /)
| Return str(self).
|
| __sub__(self, value, /)
| Return self-value.
|
| astimezone(...)
| tz -> convert to local time in new timezone tz
|
| combine(...) from builtins.type
| date, time -> datetime with same date and time fields
|
| ctime(...)
| Return ctime() style string.
|
| date(...)
| Return date object with same year, month and day.
|
| dst(...)
| Return self.tzinfo.dst(self).
|
| fromtimestamp(...) from builtins.type
| timestamp[, tz] -> tz's local time from POSIX timestamp.
|
| isoformat(...)
| [sep] -> string in ISO 8601 format, YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].
| sep is used to separate the year from the time, and defaults to 'T'.
| timespec specifies what components of the time to include (allowed values are 'auto', 'hours', 'minutes', 'seconds', 'milliseconds', and 'microseconds').
|
| now(tz=None) from builtins.type
| Returns new datetime object representing current time local to tz.
|
| tz
| Timezone object.
|
| If no tz is specified, uses local timezone.
|
| replace(...)
| Return datetime with new specified fields.
|
| strptime(...) from builtins.type
| string, format -> new datetime parsed from a string (like time.strptime()).
|
| time(...)
| Return time object with same time but with tzinfo=None.
|
| timestamp(...)
| Return POSIX timestamp as float.
|
| timetuple(...)
| Return time tuple, compatible with time.localtime().
|
| timetz(...)
| Return time object with same time and tzinfo.
|
| tzname(...)
| Return self.tzinfo.tzname(self).
|
| utcfromtimestamp(...) from builtins.type
| Construct a naive UTC datetime from a POSIX timestamp.
|
| utcnow(...) from builtins.type
| Return a new datetime representing UTC day and time.
|
| utcoffset(...)
| Return self.tzinfo.utcoffset(self).
|
| utctimetuple(...)
| Return UTC time tuple, compatible with time.localtime().
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| fold
|
| hour
|
| microsecond
|
| minute
|
| second
|
| tzinfo
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| max = datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)
|
| min = datetime.datetime(1, 1, 1, 0, 0)
|
| resolution = datetime.timedelta(0, 0, 1)
|
| ----------------------------------------------------------------------
| Methods inherited from date:
|
| __format__(...)
| Formats self with strftime.
|
| fromordinal(...) from builtins.type
| int -> date corresponding to a proleptic Gregorian ordinal.
|
| isocalendar(...)
| Return a 3-tuple containing ISO year, week number, and weekday.
|
| isoweekday(...)
| Return the day of the week represented by the date.
| Monday == 1 ... Sunday == 7
|
| strftime(...)
| format -> strftime() style string.
|
| today(...) from builtins.type
| Current date or datetime: same as self.__class__.fromtimestamp(time.time()).
|
| toordinal(...)
| Return proleptic Gregorian ordinal. January 1 of year 1 is day 1.
|
| weekday(...)
| Return the day of the week represented by the date.
| Monday == 0 ... Sunday == 6
|
| ----------------------------------------------------------------------
| Data descriptors inherited from date:
|
| day
|
| month
|
| year
datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2017, 4, 27, 23, 4, 8, 142947) # 年、月、日、时、分、秒、微秒
>>> now.year
2017
>>> now.day
27
>>> now.month
4
>>> now.hour
23
timedelta
时间差,日期和时间可以相加减,得到一个timedelta对象
>>> birthday = datetime.date(1991, 12, 10)
>>> now = datetime.date.now()
>>> today - birthday
datetime.timedelta(9273)>>>
>>> datetime.datetime.now() - datetime.datetime(1991,12,10)
datetime.timedelta(9273, 15500, 135084)
综合运用
将时间格式转换成str类型
>>> datetime.datetime.now().strftime('%Y/%m/%d')
'2017/04/27'
>>> datetime.datetime.now().strftime('%Y-%m-%d')
'2017-04-27'
>>> datetime.date.today().strftime('%Y/%m/%d')
'2017/04/27'
>>> datetime.datetime.now().strftime('%Y%m%d%H%M%S')
''
>>> datetime.time(18,20,31).strftime('%H-%M-%S')
'18-20-31'
>>> datetime.time(18,20,31).strftime('%H:%M:%S')
'18:20:31'
将str转换成日期和时间类型
>>> s = '2018-09-22'
>>> datetime.datetime.strptime(s, '%Y-%m-%d')
datetime.datetime(2018, 9, 22, 0, 0)
>>> s = '2018-09-22-17-22'
>>> datetime.datetime.strptime(s, '%Y-%m-%d-%H-%M')
datetime.datetime(2018, 9, 22, 17, 22)
时间差,有这样的需求,要得到前后多少天、前后多少分钟
# 3天前
>>> (datetime.datetime.now() - datetime.timedelta(days=3)).strftime('%Y%m%d')
''
# 3天后
>>> (datetime.datetime.now() + datetime.timedelta(days=3)).strftime('%Y%m%d')
''
# 15分钟前
>>> (datetime.datetime.now() - datetime.timedelta(seconds=900)).strftime('%Y%m%d%H%M%S')
''
# 15分钟后
>>> (datetime.datetime.now() + datetime.timedelta(seconds=900)).strftime('%Y%m%d%H%M%S')
''
比如输入你的生日,算你来了这个世界上有多少天
>>> birthday = datetime.date(1991, 12, 10)
>>> now = datetime.date.today()
>>> result = now - birthday
>>> result.days
9273
time
我觉得功能上和datetime差不多
>>> time.localtime()
time.struct_time(tm_year=2017, tm_mon=4, tm_mday=30, tm_hour=4, tm_min=45, tm_sec=38, tm_wday=6, tm_yday=120, tm_isdst=0)
>>> time.sleep(1) # 等待多少秒
>>> time.strftime('%Y-%m-%d %H:%M:%S') # 时间格式化
'2017-04-30 04:46:21'
>>> time.ctime()
'Sun Apr 30 17:46:02 2017'