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‘)
‘20170427223159‘
>>> 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‘)
‘20170424‘
# 3天后
>>> (datetime.datetime.now() + datetime.timedelta(days=3)).strftime(‘%Y%m%d‘)
‘20170501‘
# 15分钟前
>>> (datetime.datetime.now() - datetime.timedelta(seconds=900)).strftime(‘%Y%m%d%H%M%S‘)
‘20170428005835‘
# 15分钟后
>>> (datetime.datetime.now() + datetime.timedelta(seconds=900)).strftime(‘%Y%m%d%H%M%S‘)
‘20170428005835‘

比如输入你的生日,算你来了这个世界上有多少天

>>> 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‘
时间: 2024-11-06 07:24:21

datetime & time的相关文章

python时间处理模块 datetime time模块 deltetime模块

1 首先介绍time模块,因为简单 python 自带模块 本人使用time模块,只使用两个函数 time函数和sleep函数 import time a.     time.time()   函数 返回unix时间  常用作两个时间差的计算 b.     time.sleep()  休眠多久,精度为子秒(subsecond) In [90]: t1 = time.time() In [91]: t1 Out[91]: 1461400225.877932 In [92]: time.sleep(

C#中的DateTime和TimeSpan

最近写个小程序用到了这两个类型,现在对它们进行总结区分. DateTime是类,表示时间上的某一刻. TimeSpan是结构,表示一个时间间隔. DateTime类型包含了表示某个日期(年.月.日)的数据以及时间值,可以使用指定的成员以各种形式将他们格式化. TimeSpan结构允许你方便地使用各个成员定义和转换时间单位. TimeSpan类型可以直接进行相减运算,运算数据为TimeSpan类型.也可以调用Subtract方法进行相减运算. 输出结果为:

asp 之 让实体中字段类型为DateTime的字段只显示日期不显示时间

       在我们平时的工作开发中,我们通常会遇到这样的一个问题:某个实体的某个字段是DateTime类型的,可是我们在界面上只想让它显示日期不显示时间! 一个订单实体: //订单类 public class order { //订单ID public int id{get;set;} //物品ID public int resId{get;set;} //物品名称 public string resName { get; set; } //物品价格 public decimal price

Mysql 插入时间时报错Incorrect datetime value: &#39;&#39; for column &#39;createtime&#39;

在网上找了很多方法总结如下: 1.MySQL驱动版本的问题.这种一般是在mYSQL版本更新了之后才会报错.解决方法在jdbc里添加"&useOldAliasMetadataBehavior=true" 2.可能是datetime的格式问题. datetime 以'YYYY-MM-DD HH:MM:SS'格式检索和显示DATETIME值.支持的范围为'1000-01-01 00:00:00'到'9999-12-31 23:59:59'TIMESTAMP值不能早于1970或晚于20

Sql 中常用日期转换Convert(Datetime)

CONVERT(data_type,expression[,style]) convert(varchar(10),字段名,转换格式) 说明:此样式一般在时间类型(datetime,smalldatetime)与字符串类型(nchar,nvarchar,char,varchar)相互转换的时候才用到. 语句 结果SELECT CONVERT(varchar(100), GETDATE(), 0) 07 15 2009 4:06PMSELECT CONVERT(varchar(100), GETD

从 datetime2 数据类型到 datetime 数据类型的转换产生一个超出范围的值

最近在ASP.NET MVC中遇到一个问题,如题,在使用EF数据模型的时候,要去添加一条新的数据到Sqlserver数据库,在之前项目中并没有出现该异常,所以去扒了扒demo,发现有几个字段(数据库类型为datetime)savechange的时候默认绑定了datetime.now.问题就在这里,我的新项目并没有给定这几个字段的数据.下面总结下: 触发该错误的条件如下: SQL Server数据库版本中的字段类型为datetime2 数据库中,某个要进行Add或者Edit的字段的数据类型为dat

time模块和datetime模块

http://www.cnblogs.com/tkqasn/p/6001134.html 一.time模块 time模块中时间表现的格式主要有三种: a.timestamp时间戳,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量 b.struct_time时间元组,共有九个元素组. c.format time 格式化时间,已格式化的结构使时间更具可读性.包括自定义格式和固定格式. 1.时间格式转换图: 2.主要time生成方法和time格式转换方法实例: import ti

python 时间模块小结(time and datetime)

一:经常使用的时间方法 1.得到当前时间 使用time模块,首先得到当前的时间戳 In [42]: time.time() Out[42]: 1408066927.208922 将时间戳转换为时间元组 struct_time In [43]: time.localtime(time.time()) Out[43]: time.struct_time(tm_year=2014, tm_mon=8, tm_mday=15, tm_hour=9, tm_min=42, tm_sec=20, tm_wd

time&amp;datetime&amp;random模块

import time 1.print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来 2.print(time.altzone) #返回与utc时间的时间差,以秒计算3.print(time.asctime()) #返回时间格式"Thu Apr 13 21:46:21 2017", 4.print(time.localtime()) #返回本地时间 的s

mysql 存储 date , datetime问题,初步

1. java 里的 Date date = new Date()(java.util.Date) 得到  Thu Nov 03 22:19:43 CST 2016, 通过Timestamp stamp = new Timestamp(date.getTime()); 可以得到 2016-11-03 22:22:31.871. 后一种样式可以放在mysql datatime字段类型里 2. 如何通过mysql语言插入datetime类型