【Python】python内置模块 time 和 datetime 模块 详解

time:

  时间相关的操作,时间有三种表示方式:

  • 时间戳               1970年1月1日之后的秒,即:time.time()
  • 格式化的字符串    2014-11-11 11:11,    即:time.strftime('%Y-%m-%d')
  • 结构化时间          元组包含了:年、日、星期等... time.struct_time    即:time.localtime()

其常包含的函数有:

  • time.time(): 返回一个时间戳
  • time.asctime([t]): 转换gmtime()和localtime()返回的元组或struct_time为string.
  • time.clock(): 在第一次调用的时候, 返回程序运行的时间. 第二次之后返回与之前的间隔.
  • time.ctime([secs]): 将时间戳转换为时间字符串, 如没有提供则返回当前的时间字符串,并与asctime(localtime())一样.
  • time.gmtime([secs]): 将时间戳转化为, UTC 时区的struct_time.
  • time.localtime([secs]): 类似gmtime()但会把他转换成本地时区.
  • time.mktime(t): struct_time 转化为时间戳.
  • time.sleep(secs): 线程推迟指定时间, 以秒为单位.
  • time.strftime(format[,t]): 根据参数转换一个sturc_time或元组为字符串.
  • time.strptime(string[, format]): 与strftime相反,返回一个struct_time.

time模块中常用的格式化字符串

  • %y 两位数的年份 00 ~ 99.
  • %Y 四位数的年份 0000 ~ 9999
  • %m 月份 01 ~ 12.
  • %d day 01 ~ 31.
  • %H 时 00 ~ 23.
  • %I 时 01 ~ 12.
  • %M 分 00 ~ 59.
  • %S 秒 00 ~ 61.

如果想知道更具体的,就参考这个链接吧  https://docs.python.org/zh-cn/3.7/library/time.html

datetime:

datetime模块提供对于日期和时间进行简单或复杂的操作. datetime 模块提供了一下的可用类型(Available Types).

datetime.MINYEAR 和 datetime.MAXYEAR 模块常量表示datetime接受的范围

  • class datetime.date: 一个理想化的日期, 提供year, month, day属性
  • class datetime.time: 一个理想化的时间, 提供hour, minute, second, microsecond, tzinfo.
  • class datetime.datetime: 日期和时间的组合.提供year, month, day, hour, minute, second, microsecond, tzinfo.
  • class datetime.timedelta: 表达两个date,time和datetime持续时间内的微妙差异.
  • class datetime.tzinfo: 时间对象的抽象基类.
from datetime import timedelta, datetime
 
a = datetime.now()
b = timedelta(days=7)

print(a)
print(a-b)

 如果想知道更具体的,就参考这个链接吧  https://docs.python.org/zh-cn/3.7/library/datetime.html#module-datetime

下面在说一下类和类的方法:

date类:

class datetime.date(year, month, day)
  # All arguments are required. Arguments may be ints or longs.
  # 所有参数都是必须的. 参数可能是 int 或 long.
  MINYEAR <= year <= MAXYEAR
  1<= month <= 12
  1<= day <= number of days in the given month and year.(随着月份和年份)

     如果参数脱离给的范围会抛出, valueError.

类方法:

date.today():放回当前的本地日期,等价于`date.fromtimestamp(time.time())`.

from datetime import date
 
print( date.today())

date.fromtimestamp(timestamp):根据提供的时间戳返回local date. 时间戳常用于对时间类型的存储.

import time
from datetime import date
 

print (time.time())
print (date.fromtimestamp(time.time()))

date.fromordinal(ordinal):根据提供的Gregorian日历返回date.

类属性:

  • date.min: 返回 date(MINYEAR, 1, 1).
  • date.max: 返回 date(MAXYEAR, 12, 31).
  • date.year: 返回 年, MINYEAR和MAXYEAR之间
  • date.month: 返回 月, 1到12月之间
  • date.day: 返回 1到 n 之间.
d = date(2020, 8, 7)
print (d.year, d.month, d.day)

date常见到的方法:

  • date.replace(year, month, day):返回一个相同值的data对象, 除了这些参数给关键字指定新的值.
  • date.timetuple(): 返回一个time.struct_time对象.
  • date.toordinal(): 返回一个Gregoian Calendar对象.
  • date.weekday(): 返回day of the week. 星期一为0,星期日为6.
  • date.isoweekday(): 返回day of the week. 星期一为1,星期日为7.
  • date.isocalendar(): 返回一个三元组, (ISO year, ISO week number, ISO weekday).
  • date.isoformat(): 返回 一个'YYYY-MM-DD'的字符串格式.
  • date.ctime(): 返回一个字符串日期, d.ctime() 等同于 time.ctime(time.mktime(d.timetuple())).
  • date.strftime(format): 返回一个字符串日期, 格式自定义.

datetime类:

datetime 对象是一个单一的对象, 包含所有date和time对象的信息.

class datetime.datetime(year, month, day[, hour
                    [, minute
                    [, second
                    [, microsecond
                    [, tzinfo]]]]])
  # The year, month and day arguments are required.
  MINYEAR <= year <= MAXYEAR
  1 <= month <= 12
  1 <= day <= n
  0 <= hour < 24
  0 <= minute < 60
  0 <= second < 60
  0 <= microsecond < 10**6

类方法:

  • datetime.today(): 返回当前本地datetime.随着 tzinfo None. 这个等同于datetime.fromtimestamp(time.time()).
  • datetime.now([tz]): 返回当前本地日期和时间, 如果可选参数tz为None或没有详细说明,这个方法会像today().
  • datetime.utcnow(): 返回当前的UTC日期和时间, 如果tzinfo None ,那么与now()类似.
  • datetime.fromtimestamp(timestamp[, tz]): 根据时间戳返回本地的日期和时间.tz指定时区.
  • datetime.utcfromtimestamp(timestamp): 根据时间戳返回 UTC datetime.
  • datetime.fromordinal(ordinal): 根据Gregorian ordinal 返回datetime.
  • datetime.combine(date, time): 根据date和time返回一个新的datetime.
  • datetime.strptime(date_string, format): 根据date_string和format返回一个datetime.
from datetime import datetime
 
print (datetime.today())
print (datetime.now())
 
t = time.time() 
print (t)
print (datetime.fromtimestamp(t))
 
from datetime import datetime, date, time
 
a = date(2020,8, 7)
b = time(14, 13, 34)

print (datetime.combine(a, b))

实例方法:

  • datetime.date(): 返回相同年月日的date对象.
  • datetime.time(): 返回相同时分秒微秒的time对象.
  • datetime.replace(kw): kw in [year, month, day, hour, minute, second, microsecond, tzinfo], 与date类似.

类属性:

  • datetime.min: datetime(MINYEAR, 1, 1).
  • datetime.max: datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999).

time类:

time 代表本地(一天内)时间.

class datetime.time([hour
          [, minute
          [, second 
          [, microsecond
          [, tzinfo]]]]])
  # All arguments are optional.
  # 所有参数都是可选的.
  0 <= hour < 24
  0 <= minute < 60
  0 <= second < 60
  0 <= microsesond < 10**6

最后来个例子大合集:

#_*_coding:utf-8_*_

import time

# print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来
# print(time.altzone)  #返回与utc时间的时间差,以秒计算\
# print(time.asctime()) #返回时间格式"
# print(time.localtime()) #返回本地时间 的struct time对象格式
# print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式

# print(time.asctime(time.localtime())) #返回时间格式"Fri Aug 07 11:14:16 2020",
#print(time.ctime()) #返回Fri Aug 07 11:14:16 2020 格式, 同上

# 日期字符串 转成  时间戳
# string_2_struct = time.strptime("2020/08/07","%Y/%m/%d") #将 日期字符串 转成 struct时间对象格式
# print(string_2_struct)
# #
# struct_2_stamp = time.mktime(string_2_struct) #将struct时间对象转成时间戳
# print(struct_2_stamp)

#将时间戳转为字符串格式
# print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式
# print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式

#时间加减
import datetime

# print(datetime.datetime.now()) #返回 2020-08-07 12:47:03.941925
#print(datetime.date.fromtimestamp(time.time()) )  # 时间戳直接转成日期格式 2016-08-19
# print(datetime.datetime.now() )
# print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
# print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
# print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
# print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分

#
# c_time  = datetime.datetime.now()
# print(c_time.replace(minute=3,hour=2)) #时间替换
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值