import time
时间戳时间:从1970到现在的秒数,time.time()
>>> time.time()
1500964794.3408804
格式化字符串:20170627 21:30:45
元祖:struct_time共九个元素,结构化时间元祖
>>> time.localtime()
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=25, tm_hour=14, tm_min=40, tm_sec=6, tm_wday=1, tm_yday=206, tm_isdst=0)
取出年份:
>>> x = time.localtime()
>>> x
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=25, tm_hour=15, tm_min=23, tm_sec=57, tm_wday=1, tm_yday=206, tm_isdst=0)
>>> x.tm_year
2017
>>> time.gmtime()
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=25, tm_hour=7, tm_min=12, tm_sec=15, tm_wday=1, tm_yday=206, tm_isdst=0)
将结构化元祖时间转化为时间戳:
>>> x = time.localtime()
>>> x
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=25, tm_hour=14, tm_min=44, tm_sec=59, tm_wday=1, tm_yday=206, tm_isdst=0)
>>> time.mktime(x)
1500965099.0
将结构化元祖时间转化为格式化字符串时间:
>>> time.strftime("%Y-%m-%d %H:%M:%S", x)
'2017-07-25 14:44:59'
字符串格式化时间格式:format
strftime(...)
strftime(format[, tuple]) -> string
Convert a time tuple to a string according to a format specification.
See the library reference manual for formatting codes. When the time tuple
is not present, current time as returned by localtime() is used.
Commonly used format codes:
%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 Hour (24-hour clock) as a decimal number [00,23].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%z Time zone offset from UTC.
%a Locale's abbreviated weekday name.
%A Locale's full weekday name.
%b Locale's abbreviated month name.
%B Locale's full month name.
%c Locale's appropriate date and time representation.
将格式化字符串时间转化为结构化元祖时间:
strptime(...)
strptime(string, format) -> struct_time
>>> time.strptime('2017-07-25 14:44:59',"%Y-%m-%d %H:%M:%S")
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=25, tm_hour=14, tm_min=44, tm_sec=59, tm_wday=1, tm_yday=206, tm_isdst=-1)
将结构化元祖时间转化为字符串:
asctime(...)
asctime([tuple]) -> string
Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.
When the time tuple is not present, current time as returned by localtime()
is used.
>>> time.asctime(x)
'Tue Jul 25 14:44:59 2017'
将时间戳转化为string:
>>> time.ctime(time.time())
'Tue Jul 25 15:16:11 2017'
>>> time.timezone
-28800 ---->相隔8个小时,这个是秒为单位
>>> time.altzone
-32400 -----》夏令营相隔时间
import datetime
>>> datetime.datetime.now() 获取当前时间:
datetime.datetime(2017, 7, 25, 15, 17, 30, 899516)
>>> print(datetime.datetime.now()) 格式化字符串时间
2017-07-25 15:17:59.255676
获取三天后的时间:
>>> print(datetime.datetime.now() + datetime.timedelta(3))
2017-07-28 15:20:18.179573
获取三天前的时间:
>>> print(datetime.datetime.now() + datetime.timedelta(-3))
2017-07-22 15:21:25.385973
获取当前时间后三个小时:
>>> print(datetime.datetime.now() + datetime.timedelta(hours=3))
2017-07-25 18:22:05.528957
获取当前时间后30分钟:
>>> print(datetime.datetime.now() + datetime.timedelta(minutes=30))
2017-07-25 15:52:52.346930