datetime & time
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'
datetime & time的更多相关文章
- C# DateTime与时间戳转换
C# DateTime与时间戳的相互转换,包括JavaScript时间戳和Unix的时间戳. 1. 什么是时间戳 首先要清楚JavaScript与Unix的时间戳的区别: JavaScript时间戳: ...
- C# DateTime日期格式化
在C#中DateTime是一个包含日期.时间的类型,此类型通过ToString()转换为字符串时,可根据传入给Tostring()的参数转换为多种字符串格式. 目录 1. 分类 2. 制式类型 3. ...
- 在面试中忽然发现DateTime的一些...
今天说说我面试中碰到的一个小问题,在我问起DateTime为什么无法赋值NULL值,一般第一反应都认为它是值类型,不是引用类型,但随后我查阅了度娘自我学习到它是结构类型,那么随之而然就无法赋值NULL ...
- LINQ to SQL语句(14)之Null语义和DateTime
Null语义 说明:下面第一个例子说明查询ReportsToEmployee为null的雇员.第二个例子使用Nullable<T>.HasValue查询雇员,其结果与第一个例子相同.在第三 ...
- .NET DateTime类型变量作为参数时设置默认值
一个小的 Tips. .NET 中函数参数的默认值需要是编译时常量.如果参数是引用类型,可以设置Null,如果是值类型,可以设置相应的编译时常量,如整型可以用整数,但对于DateTime(结构体,值类 ...
- BCS datetime 时间区间问题
BCS 整合sql表时发现以下问题: datetime字段在列表中带了时区,比如插入12-6号的数据,在sql中显示的是12-5 date类型字段无法正确识别,插入成功但报错 LobSystem (外 ...
- C#中DateTime.Ticks属性及Unix时间戳转换
1.相关概念 DateTime.Ticks:表示0001 年 1 月 1 日午夜 12:00:00 以来所经历的 100 纳秒数,即Ticks的属性为100纳秒(1Ticks = 0.0001毫秒). ...
- WPF 自定义DateControl DateTime控件
自定义日期控件,月份选择.如下是日期的一些效果图. 具体的样式.颜色可以根据下面的代码,自己调节即可 1.日期控件的界面 <UserControl x:Class="WpfApp ...
- JavaScript 解析 Django Python 生成的 datetime 数据 时区问题解决
JavaScript 解析 Django/Python 生成的 datetime 数据 当Web后台使用Django时,后台生成的时间数据类型就是Python类型的. 项目需要将几个时间存储到数据库中 ...
- python标准模块(time、datetime及hashlib模块)
一.time,datetime模块 时间相关的操作 import time time.sleep(5) # ==> 停顿多少秒 print(time.time()) # ==> 返回时间戳 ...
随机推荐
- 来看看N多设计师笔下的Spider Man
很多电影在大获成功后,其中的人物都成了火热的IP,漫威的各类超级英雄就是个很好的例子,今天突发奇想看看各种漫画人物在插画师手中同一人物会有什么样的不同,所以以蜘蛛侠为主题,搜集了很多插画师笔下的蜘蛛侠 ...
- nginx指令中的优化(配置文件)
nginx指令中的优化(配置文件)worker_processes 8; nginx进程数,建议按照cpu数目来指定,一般为它的倍数.worker_cpu_affinity 00000001 0000 ...
- mysql完装成功后的提示。
To start mysqld at boot time you have to copysupport-files/mysql.server to the right place for your ...
- tomcat 配置域名访问应用
<Host appBase="webapps" autoDeploy="true" name="www.XXX.com" unpack ...
- ubuntu16下的/etc/resolv.conf重置的解决方案
此文件存放了网络网关信息,重启后会刷新,刷新来源有两个可能 一个是根据文件中的resolvconf目录下的resolv.conf.d目录下的base文件 另一个来源是/etc/network/inte ...
- python学习 day5 (3月6日)
字典映射,{}键值对,key 唯一的 ,可哈希,容器型数据类型 可变的(不可哈希): 字典 列表 集合 都不可做键 不可变的(可哈希): 数字 字符串 bool 元组 frozeset() 可以做键 ...
- Linux硬件信息命令大全
硬件信息 在linux系统中,有很多命令可以用于查询主机的硬件信息,有些命令仅仅针对于特定的硬件部件,比如cpu,内存等,而有些命令可以查询很多的硬件信息. 这篇帖子简单地带大家了解一下最常用的查询各 ...
- 假期训练六(poj-1753,递归+hdu-2844,多重背包)
题目一:传送门 题意:有一个4*4的棋盘,每次翻转一个棋子和它的上下左右的四个棋子,判断翻转多少次之后可以变为纯色的棋盘. 思路:总共有C(0,16)+C(1,16)+C(2,16)+……+C(16, ...
- TCP/IP协议(6):传输层之UDP
一. UDP用户数据报协议,它是一个无连接的,面向数据报的协议,它不提供可靠性但传输速度比TCP要快. UDP数据报中的“UDP长度”为两个字节,所以我们要发送的UDP数据最多支持65507大约68K ...
- CodeForces 916B Jamie and Binary Sequence (changed after round) (贪心)
题意:给定两个数字n,m,让你把数字 n 拆成一个长度为 m 的序列a1,a2,a3...am,并且∑2^ai = n,如果有多组,要求序列中最大的数最小,然后再相同就要求除了最大数字典序最大. 析: ...