`
您已经登录
  • 浏览: 43371 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

python时间处理:datetime,time,calendar

 
阅读更多
datetime模块
一,两个常量:
MINYEAR,最小年份1;
MAXYEAR,最大年份9999
 
二,五个类:
1.datetime.date(year, month, day):表示日期的类。
  1.1 date类型的具体属性:
      min:最小date---0001-01-01。
      max:最大date---9999-12-31。
      resolution:date类型的最小单位---1 day, 0:00:00。
      year:date对象对应的年,int类型。
      month:date对象对应的月,int类型。
      day:date对象对应的日,int类型。
  1.2 date类型的具体方法:
      today():返回本地当前的date。
      fromtimestamp(timestamp):根据给定的timestamp时间戳返回对应的date。
      replace(year, month, day):生成一个新的date,用指定的年月日替换。
      timetuple():回日期对应的time.struct_time对象
      weekday():返回星期,如果是星期一是返回0,返回int类型。
      isoweekday():返回标准的星期,星期一是1,返回int类型。
      isocalendar():返回(ISO year, ISO week number, ISO weekday)元组。
      isoformat():返回yyyy-mm-dd的标准日期字符串形式。
      ctime():返回一个日期字符串,如'Wed Dec 4 00:00:00 2002'
      strftime(format):自定义格式化日期字符串。
  1.3 date类型支持的操作:
操作
说明
date2 = date1 + timedelta 一个日期加上一个时间间隔等于一个新时间
date2 = date1 - timedelta
一个时间减去一个时间间隔等于一个新时间
timedelta = date2 - date1
两个时间相减等于一个时间间隔
date1 > date2
比较两个时间
 
2.datetime.time(hour[, minute[, second[, microsecond[, tzinfo]]]]):表示时间的类,tzinfo表示时区。
  2.1 time类型具体属性:
      min:最小的time类型。
      max:最大的time类型。
      resolution:time类型的最小单位,两个time对象间不能加减。
      hour:范围在24之内的int类型,对应时。
      minute:范围在60内的int类型,对应分。
      second:范围在60内的int类型,对应秒。
      microsecond:范围在1000000内的int类型,对应微妙。
      tzinfo:时区信息,默认为None。
  2.2 time类型具体方法:
      replace([hour[, minute[, second[, microsecond[, tzinfo]]]]]):通过各个参数替换time中的时分秒等信息。
      isoformat():返回标准的时间字符串,HH:MM:SS.mmmmmm,如16:02:00.000999.
      strftime(format):自定义格式时间字符串。
      utcoffset():如果tzinfo是None,则返回None。如果不是就返回tzinfo.utcoffset(None)。
      dst():如果tzinfo是None,则返回None。如果不是就返回tzinfo.dst(None)。
      tzname():如果tzinfo是None,则返回None。如果不是就返回tzinfo.tzname(None)。
注意:time之间不能进行加减,可以进行比较>,<,=
 
3.datetime.datetime(yearmonthday[, hour[, minute[, second[, microsecond[, tzinfo]]]]]):表示日期时间。
  3.1 datetime类型具体属性:
      date类型和time类型的属性datetime都具备:min,max,resolution,year,month,day,hour,minute,second,microsecond,tzinfo。
  3.2 datetime类型具体方法:
      today():返回当前本地的datetime。此时的tzinfo是None。
      now([tzinfo]):返回当前本地的datetime。
      utcnow():返回utc时区的当前的datetime。
      fromtimestamp(timestamp[, tzinfo]):根据给定的timestamp时间戳返回对应的datetime。
      utcfromtimestamp(timestamp):根据给定的timestamp时间戳返回对应的datetime,时区为标准UTC时区。
      combine(date, time):根据date和time组成一个datetime。
      strptime(date_string, format):根据format格式把date_string转换成一个datetime。
      还有包括date和time的方法datetime都具备,如strftime(format)等。
   3.3 datetime类型支持的操作:
操作
说明
datetime2 = datetime1 + timedelta 一个datetime加上一个时间间隔等于一个新datetime
datetime2 = datetime1 - timedelta
一个datetime减去一个时间间隔等于一个新datetime
timedelta = datetime2 - datetime1
两个datetime相减等于一个时间间隔
datetime1 > datetime2
比较两个datetime
 
4.datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]]):表示时间间隔,即两个时间点之间的长度。
  4.1 timedelta类型具体属性:
      min:最小的timedelta,-999999999 days, 0:00:00
      max:最大的timedelta,999999999 days, 23:59:59.999999
      resolution:timedelta的最小单位,0:00:00.000001
属性
含义
范围
days
相差的天数,不包含seconds和microsecond
-999999999 到 999999999
seconds
相差的秒杀,不计算days和microseconds
0 到 86399(一天不到一秒)
microseconds
相差的微妙,不计算days和seconds
0 and 999999
支持的操作
操作
结果
t1 = t2 + t3
 
t1 = t2 - t3
 
t1 = i * t2
 
t1 = t2 // 2
向下取整,余数部分被丢弃
+t1
 
-t1
取反操作,等价于timedetal(-t1.days, -t1.seconds, -t1.microseconds)和 t1* -1
abs(t1)
绝对值,等价于: +t 当 t.days >= 0,  -t 当 t.days < 0
str(t1)
返回字符串,格式为: [D day[s], ][H]H:MM:SS[.UUUUUU]
repr(t1)
返回字符串,格式为: datetime.timedelta(D[, S[, U]])
  4.2 timedetal类型具体方法:
      total_seconds():返回timedetal的总的秒杀。
 
5.datetime.tzinfo:与时区有关的相关信息是一个抽象类,不能被实例化。
     如果需要使用时区就必须派生子类,并实现其几个方法。可以尝试使用第三方的包来处理时区,如pytz。
 
时间格式字符含义:日期段字符表示都是小写(除了%Y),时间段的都是大写
字符符号
含义
%a
星期的英文简写,如Sat
%A
星期的英文全写,如Wednesday
%b
月份的英文简写,如Jan
%B
月份的英文全写,如January
%c
适当语言环境下的日期和时间,如01/18/14 11:14:23
%d
日,月中的第几日,范围在[1-31]依具体月份决定
%f
微妙,范围[0-999999]
%H
小时(24小时制),范围[0-23]
%I
小时(12小时制),范围[0-11]
%j
日,年中的第几日,范围在[001-356]依具体年份定
%m
月,范围在[01-12]
%M
分,范围在[01-59]
%p
上下午,AM或者PM
%S
秒,范围[0-61],因为有闰秒等原因所以是61而非59
%U
周,一年中的第几周,范围[00-53],星期天是周的第一天,所有在新年第一个周日之前的天都算为这新一年的第0周
%w
天在这周内的天数,范围[0-6],0表示周日
%W
周,一年中的第几周,范围[00-53],星期一是周的第一天,所有在新年第一个周一之前的天都算为这新一年的第0周
%x
适当语言环境下的日期,如01/18/14
%X
适当语言环境下的时间,如11:14:23
%y
年份后两位,如14
%Y
年份,如2014
%z
与utc时间的间隔 (如果是本地时间,返回空字符串)
%Z
时区名称(如果是本地时间,返回空字符串)
%%
%
 
time模块
time模块的实现主要调用C函数的time.h库,所以各个平台可能有所不同
time中表现时间的方式有三种:
1.int型,从1970年1月1号凌晨开始到当前的秒杀,即时间戳。
2.struct_time结构体,以元组的形式表示,共有九个元素,同一个时间戳的struct_time会因为时区不同而不同。
3.格式化字符串,如UTC(通用标准时间)格式时间,中国为UTC+8。
 
一,time.struct_time
truct_time有如下九个属性,可以用属性名或者索引调用来获得对应的值。
索引(Index)属性(Attribute)值(Values)
0  tm_year(年)  比如2011 
1  tm_mon(月)  1 - 12
2  tm_mday(日)  1 - 31
3  tm_hour(时)  0 - 23
4  tm_min(分)  0 - 59
5  tm_sec(秒)  0 - 61
6  tm_wday(weekday)  0 - 6(0表示周一)
7  tm_yday(一年中的第几天)  1 - 366
8  tm_isdst(是否是夏令时)  默认为-1
 
二,time模块方法
  2.1 获得时间戳:
      time():返回当前的时间戳,自1970至当前的秒数,float类型。
      mktime(struct_time):将一个struct_time或九元元组转换成为一个时间戳。
      clock():在Windows上,在第一次调用的时候,返回的是程序运行的实际秒数;之后调用表示,从第一次调用到当前调用的间隔秒数;在UNIX系统上,它返回的是“进程时间”,它是用秒表示的浮点数(时间戳)。
 
  2.2 获得struct_time:
      localtime([secs]):无参数时返回本时区当前时间的struct_time,如果有参数时间戳secs,就是将此时间戳转换为struct_time。
      gmtime([secs]):和localtime()方法类似,无参数时gmtime()是获取0时区的当前时间。如果有参数secs,就是将此时间戳转换为struct_time。
      strptime(string[, format]):将string字符串按照format格式进行转换,获得一个struct_time。
 
  2.3 获得字符串
      ctime([secs]):无参数时,表示当前时间的字符串;有参数时,把时间戳转换为字符串形式。如:Tue Jan 21 23:07:16 2014     
      asctime([struct_time]):无参数时,表示当前时间的字符串;有参数时,把一个九元元组或者struct_time转换为字符串形式。
      strftime(format[, struct_time]):将一个struct_time或九元元组按format字符串转换为对应时间字符串;如果struct_time未传入则去time.localtime()当前时间。 
 
  2.4 其他
      sleep(secs):线程推迟指定秒杀。     
 
三,time中三种时间表现的相互转换


 

Calendar模块
Calendar是Unix cal命令的实现,可以将给定的年份/月份/日期的日历输出到设备上。
一,属性
周常量:MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
day_name:代表一周内每天的名称数组,如calendar.day_name[0]是Monday。
day_abbr:代表一周内每天名称简写数组,如calendar.day_abbr[0]是Mon。
month_name:代表一年内每月的名称数组,如calendar.month_name[1]是January。
month_abbr:代表一年内每月的简称数组,如calendar.month_abbr[1]是Jan。
 
二,方法
isleap(year):是否是闰年,是返回True,否返回False。
leapdays(year1, year2):返回year1到year2(不包含在内)之间的闰年书,如calendar.leapdays(2012, 2017)是2。
weekday(year, month, day):返回对应那天是星期几,星期一是从0开始,如weekday(2014, 1, 27)是0。
setfirstweekday(weekday):设置每周的起始是周几。
firstweekday():返回每周的起始是周几。如:先calendar.setfirstweekday(calendar.FRIDAY),则返回4。
weekheader(n):返回一周的星期的简写,n代表简写的长短。如:calendar.weekheader(3)则Fri Sat Sun Mon Tue Wed Thu
 
monthrange(year, month):返回第一个元素是指定月份的第一天是周几,第二个元素是指定月份最后一天是几号的元组。如calendar.monthrange(2014, 2)返回是(5, 28),即2014年2月1号是周六,最后一天是2月28号。
month(year, month[, w[, l]])):返回指定月的标准日历字符串
prmonth(year, month[, w[, l]])):直接打印出指定月的标准日历。等价于print calendar.month(year, month)。
 
calendar(year[, w[, l[c]]]):返回一个指定年的表征日历字符串。
prcal(year[, w[, l[c]]]):打印出一个指定年的表征日历等价于print calendar.calendar(year)。
timegm(tuple):tuple是一个时间元组,至少六元,返回一个时间戳。
 
三,类
Calendar([firstweekday])firstweekday代表每周的起始是周几,一个日历类
类中的方法:
      1. iterweekdays():返回一个iterater,里面包含着周几的七个数字形式,起始数字按firstweekday为准,如果firstweekday设置为calendar.MONDAY,则返回是0 1 2 3 4 5 6。
      
      2. itermonthdates(year, month):返回指定月的日期字符串的一个iterator,必须从每月的firstweekday开始,月末的一整周也包含在内。总共输出是7的倍数个日期。
如:cal2 = calendar.Calendar(calendar.MONDAY)
       iter1 = cal2.itermonthdates(2014, 1)
遍历输出:
       2013-12-30  到 2014-02-02
      
      3. itermonthdays(year, month) :返回指定月的日期字符串的日部分的一个iterator,必须从每月的firstweekday开始,总共输出是7的倍数个日期,非本月内的日为0填充。
如:cal = calendar.Calendar(calendar.MONDAY)
       iter = cal.itermonthdates(2014, 1)
遍历输出:
       0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 0 0
      
      4. itermonthdays2(year, month):相比 itermonthdays(year, month) 返回的iterator内的元素是一个二维元组,第一维是和termonthdays(year, month)一样,第二维是对应的星期(周一为0)。
如:cal = calendar.Calendar(calendar.MONDAY)
       iter = cal.itermonthdates(2014, 1)
遍历输出:
       (0, 0) (0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6) (6, 0) (7, 1) (8, 2) (9, 3) (10, 4) (11, 5) (12, 6) (13, 0) (14, 1) (15, 2) (16, 3) (17, 4) (18, 5) (19, 6) (20, 0) (21, 1) (22, 2) (23, 3) (24, 4) (25, 5) (26, 6) (27, 0) (28, 1) (29, 2) (30, 3) (31, 4) (0, 5) (0, 6)
 
TextCalendar([firstweekday]):此类能生成无格式的文本日期。
类中的方法:
      1. formatmonth(theyear, themonth[, w[, l]]):返回一个字符串月日历。默认w=0,l=0。w和l分别代表输出日历中的宽度和高度。
      
      2. prmonth(theyear, themonth[, w[, l]]):等同于print formatmonth(theyear, themonth[, w[, l]])。
 
      3. formatyear(theyear[, w[, l[, c[, m]]]]):返回一个字符串年日历。w,l,c,m表示列宽,行高, 每个月间的宽度, 每行显示的月数。
 
      4. pryear(theyear[, w[, l[, c[, m]]]]):等同于print formatyear(theyear[, w[, l[, c[, m]]]])。
 
HTMLCalendar([firstweekday])firstweekday代表每周的起始是周几,一个用html表格代表的日历类。
类中的方法:
      1.  formatmonth(theyear, themonth[, withyear]):返回一个html中的table,表示指定theyear年中的themonth月的日志字符串。
 

      2. formatyear(theyear[, width]):同上,返回指定theyear年的日历字符串。

      

      3. formatyearpage(theyear[, width[, css[, encoding]]]):返回完整的一个页面的html,年的日历。

    
  • 大小: 72 KB
分享到:
评论

相关推荐

    Python 对于日期时间的处理总共有三个模块:datetime 模块、time 模块、Calendar 模块

    Python 中处理日期时间的模块总共有三个:datetime 模块、time 模块、Calendar 模块。 datetime 模块是 Python 中处理日期时间的主要模块。 datetime 模块的 date 类 ------------------------- datetime 模块的 ...

    Python 时间处理datetime实例

    解答:复制代码 代码如下: import datetime, calendar lastFriday = datetime.date.today( ) oneday = datetime.timedelta(days=1) lastFriday -= oneday while lastFriday.weekday( ) != calendar.FRIDAY: last...

    Python时间模块datetime、time、calendar的使用方法

    在Python编程中,时间处理是常见的需求,而Python提供了几个内置的模块来帮助开发者处理时间相关的操作。本文将详细讨论三大时间模块:`datetime`、`time`和`calendar`。 1. **模块`datetime`** `datetime`模块是...

    python时间函数

    根据提供的标题“Python时间函数”以及描述中的关键词“函数,Python,时间操作函数”,我们可以提炼出与Python中处理时间相关的函数知识点。虽然提供的部分内容似乎与时间处理无直接关联,但我们将集中于标题和描述...

    测量程序编制 - python 56格式化输出:时间日期—time模块.pptx

    在Python编程中,处理日期和时间是常见的任务,Python提供了time和calendar两个模块来帮助我们进行日期和时间的格式化和转换。本篇主要聚焦于time模块,它提供了丰富的函数来处理时间戳、时间元组以及日期的格式化。...

    Python Datetime模块和Calendar模块用法实例分析

    Python的DateTime模块和Calendar模块是处理日期和时间的重要工具,它们提供了丰富的功能,方便开发者进行日期时间相关的计算和格式化。 DateTime模块: 1. **概述**:DateTime模块比基础的Time模块更强大,它提供了...

    Python之日期与时间处理模块(date和datetime)

    Python中提供了多个用于对日期和时间进行操作的内置模块:time模块、datetime模块和calendar模块。其中time模块是通过调用C库实现的,所以有些方法在某些平台上可能无法调用,但是其提供的大部分接口与C标准库time.h...

    详解python时间模块中的datetime模块

    Python提供了多个内置模块用于操作日期时间,像calendar,time,datetime。time模块我在之前的文章已经有所介绍,它提供的接口与C标准库time.h基本一致。相比于time模块,datetime模块的接口则更直观、更容易调用。 ...

    python时间日期函数与利用pandas进行时间序列处理详解

    python标准库包含于日期(date)和时间(time)数据的数据类型,datetime、time以及calendar模块会被经常用到。 datetime以毫秒形式存储日期和时间,datetime.timedelta表示两个datetime对象之间的时间差。 下面我们...

    Python Numpy库datetime类型的处理详解

    关于时间的处理,Python中自带的处理时间的模块就有time 、datetime、calendar,另外还有扩展的第三方库,如dateutil等等。通过这些途径可以随心所欲地用Python去处理时间。当我们用NumPy库做数据分析时,如何转换...

    Python库 | time_window-0.0.1-py3-none-any.whl

    Python库`time_window`是一个针对时间窗口操作的模块,它为Python开发者提供了处理时间范围和时间间隔的功能。在Python的生态系统中,库是扩展标准库功能的重要方式,`time_window`便是这样的一个工具,它专注于时间...

    Python库 | time_machine-2.3.0-cp38-cp38-win_amd64.whl

    通过`with`语句,你可以临时改变程序中的`datetime`, `time`, `calendar`等模块的时间,这样在该上下文内的代码就会在指定的时间点执行。 ```python from datetime import datetime from time_machine import ...

    python 常用日期处理– datetime 模块的使用

    仅以此篇记录一下个人常用的 Python 处理日期的库与函数,主要涉及的类库有 Python 自带的 datetime, time 和 calendar,以及第三方的 dateutil。说到日期处理基本上要覆盖的概念有 date, time, datetime, timezone,...

    Python中datetime模块参考手册

    Python提供了多个内置模块用于操作日期时间,像 calendar,time,datetime。time模块提供的接口与C标准库 time.h 基本一致。相比于 time 模块,datetime模块的接口则更直观、更容易调用。 模块定义了两个常量: ...

    python utc datetime转换为时间戳的方法

    总之,Python中将UTC `datetime`对象转换为时间戳时,要避免使用`time.mktime()`,而应选择`calendar.timegm()`配合`datetime`对象的`timetuple()`方法,或直接使用`timestamp()`方法(Python 3.7及以上版本)。...

    Python实用日期时间处理方法汇总

    Python提供了内置的`datetime`模块,该模块包含了多种处理日期和时间的方法。本篇文章将详细介绍Python中的一些实用日期时间处理方法。 首先,我们需要了解`datetime`模块中的主要对象类型:`datetime`、`timestamp...

Global site tag (gtag.js) - Google Analytics