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()) # ==> 返回时间戳 ...
随机推荐
- UI设计教程分享:6个不能错过的UI设计网站
Ui设计学习的人越来越多了,想要找到合适的学习资料很难,很多才接触ui设计且没有基础的同学也不知道去哪里找学习资料,虽然现在百度上很容易搜到ui设计的学习资料,但是一看不难发现,很多都是过时的学习资料 ...
- Spring ConversionService 类型转换(一)Converter
Spring ConversionService 类型转换(一)Converter Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.h ...
- UVA 10821 Constructing BST
BST: binary search tree. 题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemi ...
- Bootstrap的起步
-- Bootstrap的起步部分是对Bootstrap的基本了解,有些细节只是在后面的完善时候需要详细阅读. 最基本点还是Css 和组件部分,这部分应该先进行练习....高级阶段是Javascrip ...
- DNA计算机及DNA存储
傅里叶变换到量子水平,可编程元素到原子分子核能,都可以极大的改变有机体(高级有机体都是有寿命的,例如人类),如果可以出现机械体,核能提供能量:并结合类似高级生物大脑的有机体大脑,不断学习进化,甚至优化 ...
- Web Api 2 认证与授权 2
HTTP Message Handler 在 Web Api 2 认证与授权 中讲解了几种实现机制,本篇就详细讲解 Message Handler 的实现方式 关于 Message Handler 在 ...
- 关于Windows 8 合约
浅谈win8合约: http://www.devdiv.com/Windows_Metro-windows_metro_app_windows_contracts_-thread-131717-1-1 ...
- mybatis学习三 数据库连接池技术
1.在内存中开辟一块空间,存放多个数据库连接对象.就是Connection的多个实例2. 连接池技术有很多,c3p0,dbcp,druid,以及JDBC Tomcat Pool, JDBC Tomca ...
- LCA(最近公共祖先)模板
Tarjan版本 /* gyt Live up to every day */ #pragma comment(linker,"/STACK:1024000000,1024000000&qu ...
- rails 新建user的phonenumber字段
1.新建字段 //rails g migration add_字段名_to_表名 字段名:字段类型 rails g migration add_title_to_contents title:stri ...