Python 时间库 datetime
来源:互联网 发布:魔据大数据 编辑:程序博客网 时间:2024/05/24 04:21
dir(datetime)Out[23]: ['MAXYEAR', 'MINYEAR', '__doc__', '__name__', '__package__', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'tzinfo']
包含的数据:
MAXYEAR -- 能表示的最大年份
MINYEAR -- 能表示的最小年份
datetime_CAPI -- C语言api访问的对象,可以help(datetime.datetime_CAPI)
包含的对象:
date -- 日期对象
datetime -- 日期时间对象
time -- 时间对象
timedelta -- 日期时间间隔对象
tzinfo -- 时区信息对象
import datetimehelp(datetime)Help on built-in module datetime:NAME datetime - Fast implementation of the datetime type.FILE (built-in)CLASSES __builtin__.object date datetime time timedelta tzinfo class date(__builtin__.object) | date(year, month, day) --> date object | | Methods defined here: | | __add__(...) | x.__add__(y) <==> x+y | | __eq__(...) | x.__eq__(y) <==> x==y | | __format__(...) | Formats self with strftime. | | __ge__(...) | x.__ge__(y) <==> x>=y | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __gt__(...) | x.__gt__(y) <==> x>y | | __hash__(...) | x.__hash__() <==> hash(x) | | __le__(...) | x.__le__(y) <==> x<=y | | __lt__(...) | x.__lt__(y) <==> x<y | | __ne__(...) | x.__ne__(y) <==> x!=y | | __radd__(...) | x.__radd__(y) <==> y+x | | __reduce__(...) | __reduce__() -> (cls, state) | | __repr__(...) | x.__repr__() <==> repr(x) | | __rsub__(...) | x.__rsub__(y) <==> y-x | | __str__(...) | x.__str__() <==> str(x) | | __sub__(...) | x.__sub__(y) <==> x-y | | ctime(...) | Return ctime() style string. | | fromordinal(...) | int -> date corresponding to a proleptic Gregorian ordinal. | | fromtimestamp(...) | timestamp -> local date from a POSIX timestamp (like time.time()). | | isocalendar(...) | Return a 3-tuple containing ISO year, week number, and weekday. | | isoformat(...) | Return string in ISO 8601 format, YYYY-MM-DD. | | isoweekday(...) | Return the day of the week represented by the date. | Monday == 1 ... Sunday == 7 | | replace(...) | Return date with new specified fields. | | strftime(...) | format -> strftime() style string. | | timetuple(...) | Return time tuple, compatible with time.localtime(). | | today(...) | 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 defined here: | | day | | month | | year | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T | | max = datetime.date(9999, 12, 31) | | min = datetime.date(1, 1, 1) | | resolution = datetime.timedelta(1) 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 or longs. | | Method resolution order: | datetime | date | __builtin__.object | | Methods defined here: | | __add__(...) | x.__add__(y) <==> x+y | | __eq__(...) | x.__eq__(y) <==> x==y | | __ge__(...) | x.__ge__(y) <==> x>=y | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __gt__(...) | x.__gt__(y) <==> x>y | | __hash__(...) | x.__hash__() <==> hash(x) | | __le__(...) | x.__le__(y) <==> x<=y | | __lt__(...) | x.__lt__(y) <==> x<y | | __ne__(...) | x.__ne__(y) <==> x!=y | | __radd__(...) | x.__radd__(y) <==> y+x | | __reduce__(...) | __reduce__() -> (cls, state) | | __repr__(...) | x.__repr__() <==> repr(x) | | __rsub__(...) | x.__rsub__(y) <==> y-x | | __str__(...) | x.__str__() <==> str(x) | | __sub__(...) | x.__sub__(y) <==> x-y | | astimezone(...) | tz -> convert to local time in new timezone tz | | combine(...) | 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(...) | timestamp[, tz] -> tz's local time from POSIX timestamp. | | isoformat(...) | [sep] -> string in ISO 8601 format, YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM]. | | sep is used to separate the year from the time, and defaults to 'T'. | | now(...) | [tz] -> new datetime with tz's local day and time. | | replace(...) | Return datetime with new specified fields. | | strptime(...) | string, format -> new datetime parsed from a string (like time.strptime()). | | time(...) | Return time object with same time but with tzinfo=None. | | timetuple(...) | Return time tuple, compatible with time.localtime(). | | timetz(...) | Return time object with same time and tzinfo. | | tzname(...) | Return self.tzinfo.tzname(self). | | utcfromtimestamp(...) | timestamp -> UTC datetime from a POSIX timestamp (like time.time()). | | utcnow(...) | 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: | | hour | | microsecond | | minute | | second | | tzinfo | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T | | 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(...) | 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(...) | 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 class time(__builtin__.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 or longs. | | Methods defined here: | | __eq__(...) | x.__eq__(y) <==> x==y | | __format__(...) | Formats self with strftime. | | __ge__(...) | x.__ge__(y) <==> x>=y | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __gt__(...) | x.__gt__(y) <==> x>y | | __hash__(...) | x.__hash__() <==> hash(x) | | __le__(...) | x.__le__(y) <==> x<=y | | __lt__(...) | x.__lt__(y) <==> x<y | | __ne__(...) | x.__ne__(y) <==> x!=y | | __nonzero__(...) | x.__nonzero__() <==> x != 0 | | __reduce__(...) | __reduce__() -> (cls, state) | | __repr__(...) | x.__repr__() <==> repr(x) | | __str__(...) | x.__str__() <==> str(x) | | dst(...) | Return self.tzinfo.dst(self). | | isoformat(...) | Return string in ISO 8601 format, HH:MM:SS[.mmmmmm][+HH:MM]. | | 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: | | hour | | microsecond | | minute | | second | | tzinfo | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T | | max = datetime.time(23, 59, 59, 999999) | | min = datetime.time(0, 0) | | resolution = datetime.timedelta(0, 0, 1) class timedelta(__builtin__.object) | Difference between two datetime values. | | Methods defined here: | | __abs__(...) | x.__abs__() <==> abs(x) | | __add__(...) | x.__add__(y) <==> x+y | | __div__(...) | x.__div__(y) <==> x/y | | __eq__(...) | x.__eq__(y) <==> x==y | | __floordiv__(...) | x.__floordiv__(y) <==> x//y | | __ge__(...) | x.__ge__(y) <==> x>=y | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __gt__(...) | x.__gt__(y) <==> x>y | | __hash__(...) | x.__hash__() <==> hash(x) | | __le__(...) | x.__le__(y) <==> x<=y | | __lt__(...) | x.__lt__(y) <==> x<y | | __mul__(...) | x.__mul__(y) <==> x*y | | __ne__(...) | x.__ne__(y) <==> x!=y | | __neg__(...) | x.__neg__() <==> -x | | __nonzero__(...) | x.__nonzero__() <==> x != 0 | | __pos__(...) | x.__pos__() <==> +x | | __radd__(...) | x.__radd__(y) <==> y+x | | __rdiv__(...) | x.__rdiv__(y) <==> y/x | | __reduce__(...) | __reduce__() -> (cls, state) | | __repr__(...) | x.__repr__() <==> repr(x) | | __rfloordiv__(...) | x.__rfloordiv__(y) <==> y//x | | __rmul__(...) | x.__rmul__(y) <==> y*x | | __rsub__(...) | x.__rsub__(y) <==> y-x | | __str__(...) | x.__str__() <==> str(x) | | __sub__(...) | x.__sub__(y) <==> x-y | | total_seconds(...) | Total seconds in the duration. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | days | Number of days. | | microseconds | Number of microseconds (>= 0 and less than 1 second). | | seconds | Number of seconds (>= 0 and less than 1 day). | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T | | max = datetime.timedelta(999999999, 86399, 999999) | | min = datetime.timedelta(-999999999) | | resolution = datetime.timedelta(0, 0, 1) class tzinfo(__builtin__.object) | Abstract base class for time zone info objects. | | Methods defined here: | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __reduce__(...) | -> (cls, state) | | dst(...) | datetime -> DST offset in minutes east of UTC. | | fromutc(...) | datetime in UTC -> datetime in local time. | | tzname(...) | datetime -> string name of time zone. | | utcoffset(...) | datetime -> minutes east of UTC (negative for west of UTC). | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of TDATA MAXYEAR = 9999 MINYEAR = 1 datetime_CAPI = <capsule object "datetime.datetime_CAPI">
dir(datetime.date)Out[24]: ['__add__', '__class__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'ctime', 'day', 'fromordinal', 'fromtimestamp', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'min', 'month', 'replace', 'resolution', 'strftime', 'timetuple', 'today', 'toordinal', 'weekday', 'year']
包含的数据:
day -- 日号数值
month -- 月份数值
year -- 年份数值
max = datetime.date(9999, 12, 31)-- 最大的年、月、日的数值
min = datetime.date(1, 1, 1) -- 最小的年、月、日的数值
resolution = datetime.timedelta(1) -- 时间间隔单位为1天
包含的函数:
date(year, month, day) -- 构造函数,接受年、月、日三个参数,返回一个date object
ctime() -- 返回字符串格式的时间表示格式。不接受参数
fromordinal() -- 接受一个整型的天数数值,返回一个天数所等价的年数、月数、日数的date对象。
fromtimestamp() -- 接收一个浮点型的时间戳,返回一个从1970年起+时间戳的值对应的年、月、日的date对象。
isocalendar() -- 返回一个ISO标准的日历形式的3元元组,分别代表ISO year, week number, and weekday,不接收参数
isoformat() -- 返回一个ISO格式的日期字符串。格式为YYYY-MM-DD,不接收参数
isoweekday() -- 返回一个ISO格式的周表示。Monday == 1 ... Sunday == 7,不接收参数
replace() -- 返回一个替换指定日期字段的新date对象。参数3个可选参数,分别为year,month,day。注意替换是产生新对象,不影响原date对象。
strftime() -- 返回一个格式化的字符串形式日期。接收一个format参数,如:'%Y-%d-%m'
timetuple() -- 返回一个time的时间格式对象。等价于time.localtime()
today() -- 返回当前date或datetime对象。等价于fromtimestamp(time.time())
toordinal() -- 返回公元公历开始到现在的天数。公元1年1月1日为1
weekday() -- 返回日期表示的周期。Monday == 0 ... Sunday == 6
使用date对象中的函数,定义函数,获取本周和本月第一天的日期:
import datetimedef first_day_of_month():
'''
获取本月第一天
:return:
return datetime.date.today()- datetime.timedelta(days=datetime.datetime.now().day - 1)def first_day_of_week():
'''
'''
获取本周第一天
:return:
return datetime.date.today() - datetime.timedelta(days = datetime.date.today().weekday())if __name__ == "__main__": this_week = first_day_of_week() last_week = this_week - datetime.timedelta(days = 7) this_month = first_day_of_month() last_month = this_month - datetime.timedelta(days = (this_month - datetime.timedelta(days = 1)).day) print this_week print last_week print this_month print last_month 2017-06-052017-05-292017-06-012017-05-01
'''
dir(datetime.time)Out[33]: ['__class__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'dst', 'hour', 'isoformat', 'max', 'microsecond', 'min', 'minute', 'replace', 'resolution', 'second', 'strftime', 'tzinfo', 'tzname', 'utcoffset']包含的数据:
hour -- 小时表示数值
microsecond -- 微秒表示数值
minute -- 分钟表示数值
second -- 秒表示数值
tzinfo -- 时区表示数值
max = datetime.time(23, 59, 59, 999999) -- 最大的时间表示数值
min = datetime.time(0, 0) -- 最小的时间表示数值
resolution = datetime.timedelta(0, 0, 1) -- 时间间隔单位为分钟
包含的函数:
time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) -- 构造函数,返回一个time对象。所有参数均为可选
dst() -- 返回时区信息的描述。如果实例是没有tzinfo参数则返回空
isoformat() -- 返回ISO 8601格式字符串, HH:MM:SS[.mmmmmm][+HH:MM].
replace() -- 返回一个替换指定时间字段的新time对象。4个可选参数,分别为hour,minute,second,microsecond。注意替换是产生新对象,不影响原time对象。
strftime() -- 接收一个format参数,返回一个对应格式的字符串。如:'%H:%M:%S'
tzname() -- 返回时区的名称。如果实例是没有tzinfo参数则返回空
utcoffset() -- 返回self.tzinfo.utcoffset(self)
dir(datetime.datetime)Out[25]: ['__add__', '__class__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'astimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fromordinal', 'fromtimestamp', 'hour', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'microsecond', 'min', 'minute', 'month', 'now', 'replace', 'resolution', 'second', 'strftime', 'strptime', 'time', 'timetuple', 'timetz', 'today', 'toordinal', 'tzinfo', 'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'weekday', 'year']继承自date的数据:
day
month
year
继承自date的函数:
fromordinal(...)
isocalendar(...)
isoweekday(...)
strftime(...)
today(...)
toordinal(...)
weekday(...)
包含的数据:
hour
microsecond
minute
second
tzinfo
max = datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)
min = datetime.datetime(1, 1, 1, 0, 0)
resolution = datetime.timedelta(0, 0, 1)
包含的函数:
datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]]) -- 构造函数,返回一个datetime对象。year, month, day为必选参数
astimezone(...) -- 根据给定的timezone对象,返回转换为本地时区的timezone对象。
combine(...) -- 根据给定date, time对象合并后,返回一个对应值的datetime对象。
ctime(...) -- 返回ctime格式的字符串。
date(...) -- 返回具有相同year, month, day的date对象
dst(...) -- 返回self.tzinfo.dst(self).
fromtimestamp(...) -- 根据时间戳数值,返回一个datetime对象。
isoformat(...) -- 返回ISO 8601格式的字符串,如:YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM]
now(...) -- 根据给定的时区,返回当地的当前时间。
replace(...) -- 返回一个替换了指定日期时间字段的新datetime对象
strptime(...) -- 根据string, format2个参数,返回一个对应的datetime对象。
time(...) -- 返回一个带有相同time,但没有tzinfo的time对象。
timetuple(...) -- 返回一个时间元素, 等价于time.localtime().
timetz(...) -- 返回一个带有相同time和tzinfo的time对象。
tzname(...) -- 返回self.tzinfo.tzname(self).
utcfromtimestamp(...) -- 返回UTC时间戳的datetime对象,时间戳值为time.time()
utcnow(...) -- 返回UTC当前时间的datetime对象.
utcoffset(...) -- Return self.tzinfo.utcoffset(self).
utctimetuple(...) -- 返回UTC时间元组对象, 等价于time.localtime().
说明:
datetime.time对象调用了time模块的基础方法。并封装之。
datetime.date对象同样调用了time模块的基础方法,并封装之。
datetime.datetime对象继承了datetime.date类,并调用了time模块的方法。
import datetime"""datetime的功能强大能支持0001年到9999年""""""当前时间返回的是一个datetime类型now方法有个参数tz,设置时区类型。如果没有和方法today的效果一样"""now = datetime.datetime.now()#UTC时间datetime.datetime.utcnow()attrs = [("year","年"),('month',"月"),("day","日"),('hour',"小时"),( 'minute',"分"),( 'second',"秒"),( 'microsecond',"毫秒"),('min',"最小"),( 'max',"最大"),]for k,v in attrs: "now.%s = %s #%s" % (k,getattr(now, k),v)"""返回一个time结构"""now.timetuple() """返回一个date类型"""now.date()"""返回一个time类型"""now.time()"""当前星期几。星期一是0,星期于是6注意这里是方法,不是属性哦。"""now.weekday()"""当前星期几。星期一是1,星期于是7注意这里是方法,不是属性哦。"""now.isoweekday()"""修改当前时间。比如修改成当月1号"""now.replace(day=1)past = datetime.datetime(2010,11,12,13,14,15,16)"""进行比较运算返回的是timedelta类型"""now-past"""转成字符串详细规则见Time篇"""strdatetime = now.strftime("%Y-%m-%d %H:%M:%S")"""字符串生成datetime对象"""datetime.datetime.strptime(strdatetime, "%Y-%m-%d %H:%M:%S")Out[69]: datetime.datetime(2017, 6, 5, 16, 30, 28)
dir(datetime.timedelta)Out[36]: ['__abs__', '__add__', '__class__', '__delattr__', '__div__', '__doc__', '__eq__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__pos__', '__radd__', '__rdiv__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmul__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'days', 'max', 'microseconds', 'min', 'resolution', 'seconds', 'total_seconds']包含的数据:
days -- 天数
microseconds -- 微秒数(>= 0 and less than 1 second).
seconds -- 秒数 (>= 0 and less than 1 day).
max = datetime.timedelta(999999999, 86399, 999999)
min = datetime.timedelta(-999999999)
resolution = datetime.timedelta(0, 0, 1)
包含的函数:
timedelta() -- 构造函数,接收3个参数,天、秒、微秒
total_seconds() -- 时间间隔的总秒数
常用时间转换及处理函数:
import datetime#获取当前时间a = datetime.datetime.now()print a2017-06-05 16:26:11.957000
# 当前时间加上半小时
b = a + datetime.timedelta(hours = 0.5)print b2017-06-05 16:56:11.957000
# 格式化字符串输出
c = b.strftime('%Y-%m-%d %H:%M:%S')print c2017-06-05 16:56:11
- Python 时间库 datetime
- python datetime时间处理
- python datetime处理时间
- python datetime处理时间
- python datetime处理时间
- python datetime处理时间
- python datetime处理时间
- python datetime处理时间
- python - datetime时间相加
- python 时间模块: datetime
- python datetime处理时间
- python datetime处理时间
- python datetime处理时间
- python datetime处理时间
- Python-datetime 获取时间
- python 时间模块: datetime
- python时间处理之datetime
- python时间处理之datetime
- scala编写的数据库连接池
- 网页编程---生成图片验证码技术
- jQuery事件操作
- spiral-matrix
- Visual Studio 通过mysql-connector-net连接MySQL
- Python 时间库 datetime
- 动态规划
- Java面试题集(181-185)
- nodejs入门
- android常用控件归类(一)
- Myeclipse中如何创建spring配置文件
- spring学习笔记(一)
- html显示数据库中的字段内容为sql语句时,出现隐藏了换行等字符的问题解决
- VI操作--跳到最后一行的最后一个字符