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的更多相关文章

  1. C# DateTime与时间戳转换

    C# DateTime与时间戳的相互转换,包括JavaScript时间戳和Unix的时间戳. 1. 什么是时间戳 首先要清楚JavaScript与Unix的时间戳的区别: JavaScript时间戳: ...

  2. C# DateTime日期格式化

    在C#中DateTime是一个包含日期.时间的类型,此类型通过ToString()转换为字符串时,可根据传入给Tostring()的参数转换为多种字符串格式. 目录 1. 分类 2. 制式类型 3. ...

  3. 在面试中忽然发现DateTime的一些...

    今天说说我面试中碰到的一个小问题,在我问起DateTime为什么无法赋值NULL值,一般第一反应都认为它是值类型,不是引用类型,但随后我查阅了度娘自我学习到它是结构类型,那么随之而然就无法赋值NULL ...

  4. LINQ to SQL语句(14)之Null语义和DateTime

    Null语义 说明:下面第一个例子说明查询ReportsToEmployee为null的雇员.第二个例子使用Nullable<T>.HasValue查询雇员,其结果与第一个例子相同.在第三 ...

  5. .NET DateTime类型变量作为参数时设置默认值

    一个小的 Tips. .NET 中函数参数的默认值需要是编译时常量.如果参数是引用类型,可以设置Null,如果是值类型,可以设置相应的编译时常量,如整型可以用整数,但对于DateTime(结构体,值类 ...

  6. BCS datetime 时间区间问题

    BCS 整合sql表时发现以下问题: datetime字段在列表中带了时区,比如插入12-6号的数据,在sql中显示的是12-5 date类型字段无法正确识别,插入成功但报错 LobSystem (外 ...

  7. C#中DateTime.Ticks属性及Unix时间戳转换

    1.相关概念 DateTime.Ticks:表示0001 年 1 月 1 日午夜 12:00:00 以来所经历的 100 纳秒数,即Ticks的属性为100纳秒(1Ticks = 0.0001毫秒). ...

  8. WPF 自定义DateControl DateTime控件

    自定义日期控件,月份选择.如下是日期的一些效果图. 具体的样式.颜色可以根据下面的代码,自己调节即可    1.日期控件的界面 <UserControl x:Class="WpfApp ...

  9. JavaScript 解析 Django Python 生成的 datetime 数据 时区问题解决

    JavaScript 解析 Django/Python 生成的 datetime 数据 当Web后台使用Django时,后台生成的时间数据类型就是Python类型的. 项目需要将几个时间存储到数据库中 ...

  10. python标准模块(time、datetime及hashlib模块)

    一.time,datetime模块 时间相关的操作 import time time.sleep(5) # ==> 停顿多少秒 print(time.time()) # ==> 返回时间戳 ...

随机推荐

  1. Spring MVC 数据绑定和表单标签库

    数据绑定是将用户输入绑定到领域模型的一种特性.作用是将 POJO 对象的属性值与表单组件的内容绑定. 数据绑定的好处: 1. 类型总是为 String 的 HTTP 请求参数,可用于填充不同类型的对象 ...

  2. [Robot Framework] 执行时报 webdriver 异常

    在用Robot Framework通过Selenium2Library做web界面自动化测试的时候,报webdriver的错误: 此种情况是因为WebDriver的版本与浏览器的版本不对应. WebD ...

  3. PHP图片处理库Grafika详细教程

    转载自51CTO 开发频道 1.图像基本处理:http://developer.51cto.com/art/201611/520928.htm 2.图像特效处理模块:http://developer. ...

  4. mac install brew

    $ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" ...

  5. json ubuntu下安装

    1.首先安装scons scons是linux下的自动构建工具,类似cmake. 下载地址wget http://prdownloads.sourceforge.net/scons/scons-2.2 ...

  6. 关于 construct object opp

    constructor 定义和用法 constructor 属性返回对创建此对象的数组函数的引用. 语法 object.constructor 实例 例子 1 在本例中,我们将展示如何使用 const ...

  7. 买铅笔(NOIP2016)

    先给题目链接:买铅笔 这题非常水,没啥可分析的,先给代码: #include<bits/stdc++.h> //1 using namespace std; int main(){ int ...

  8. one or more

    想到以后如果一直都是这样,那么以后的生活是多么多么可怕啊. 感觉毫无期盼.没有意义. 如果变得理所当然那是多么多么让人害怕的事,吓得让人发抖. 所以在以后漫长的岁月里,还是一个人吧 如果相互看不惯,感 ...

  9. 数据分析处理库pandas及可视化库Matplotlib

    一.读取文件 1)读取文件内容 import pandas info = pandas.read_csv('1.csv',encoding='gbk') # 获取文件信息 print(info) pr ...

  10. servler中表单加了enctype="multipart/form-data"属性后request就接收不到表单传过来的值了

    在解决博问node.js接受参数的时候,发现当form中添加enctype:"multipart/form-data",后台确实获取不到数据,于是跑到百度上查了一下,终于明白为什么 ...