笔记-python-standard library-8.1 data types-datetime
笔记-python-standard library-8.1 data types-datetime
1. Datatimes
本章节内容为日期和时间处理类和方法。
1.1. datetime-basic date and time types
source code: Lib/datetime.py
datetime模块提供了日期和时间处理类,重点是各种格式化的输出。
时间包括两种,世界时和当地时间。
datetime和time对象可以选定时区。
datetime模块提供了下列常量:
datetime.MINYEAR,datetime.MAXYEAR分别是1和9999。
相关模块calendar日历功能,time时间访问和转换
1.1.1. 可用的类型
datetime.date:表示日期
datetime.time:表示时间
datetime.datetime:表示日期+时间
datetime.timedelta:表示两个日期,时间或日期+时间之间的差值
datetime.tzinfo:时区相关信息
datetime.timezone
类继承关系图:
object
timedelta
tzinfo
timezone
time
date
datetime
1.1.2. timedelta objects
timedelta:两个时间之差。
class datetime.timedelta(days=0, seconds=0,microseconds=0,milliseconds=0,minutes=0, hours=0,weeks=0)
实例属性(只读):
|
Attribute |
Value |
|
days |
Between -999999999 and 999999999 inclusive |
|
seconds |
Between 0 and 86399 inclusive |
|
microseconds |
Between 0 and 999999 inclusive |
支持的操作
|
t1 = t2+t3 or t1= t2-t3 |
|
|
t1= t2*I |
|
|
f = t2/t3 |
return a float object |
|
t1 = t2//i |
|
|
t1 = t2%t3 |
|
|
q,r = divmod(t1,t2) |
实例方法:
timedelta.total_seconds() 返回时间差,以秒为单位。
1.1.3. date objects
class datetime.date(year,month,day)
class methods:
date.today() 返回当日日期
date.fromtimestamp(timestamp) 根据时间戳返回日期
date.fromordinal(ordinal) 将Gregorian日历时间转换为date对象
class attributes:
date.year, date.month, date.day
supported operations:
|
Operation |
Result |
|
date2 = date1 + timedelta |
date2 is timedelta.days days removed from date1. (1) |
|
date2 = date1 - timedelta |
Computes date2 such that date2 + timedelta == date1. (2) |
|
timedelta = date1 - date2 |
(3) |
|
date1 < date2 |
date1 is considered less than date2 when date1 precedes date2 in time. (4) |
instance methods:
date.replace(year=self.year, month=self.month, day=self.day)
根据参数返回一个替代后的日期。
date.timetuple()
Return a time.struct_time such as returned by time.localtime(). The hours, minutes and seconds are 0, and the DST flag is -1. d.timetuple()is equivalent to time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1)), where yday = d.toordinal() - date(d.year, 1,1).toordinal() + 1 is the day number within the current year starting with 1 for January 1st.
示例:
>>> a = datetime.date(2017,3,22)
>>> a.timetuple() time.struct_time(tm_year=2017, tm_mon=3, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=81, tm_isdst=-1)
>>> a.timetuple().tm_year
2017
>>> a.timetuple().tm_mon
3
>>> a.timetuple().tm_mday
22
date.weekday()
以数值形式返回星期,注意星期一是0,星期天是6。
date.isoweekday()
与上一函数相同,但星期数值是1-7
date.isocalendar()
Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
date.isoformat()
Return a string representing the date in ISO 8601 format, ‘YYYY-MM-DD’. For example, date(2002, 12, 4).isoformat() == '2002-12-04'.
date.__str__()
等效于date.isoformat()
date.ctime()
返回特定格式的日期 date(2002, 12, 4).ctime() == 'Wed Dec 4 00:00:00 2002'.
date.strftime(format)
date.__format__(format)
都是返回特定格式的日期字符串。
下面是一些日期格式转换的示例:
>>> from datetime import date
>>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
>>> d
datetime.date(2002, 3, 11)
>>> t = d.timetuple()
>>> for i in t:
... print(i)
2002 # year
3 # month
11 # day
0
0
0
0 # weekday (0 = Monday)
70 # 70th day in the year
-1
>>> ic = d.isocalendar()
>>> for i in ic:
... print(i)
2002 # ISO year
11 # ISO week number
1 # ISO day number ( 1 = Monday )
>>> d.isoformat()
'2002-03-11'
>>> d.strftime("%d/%m/%y")
'11/03/02'
>>> d.strftime("%A %d. %B %Y")
'Monday 11. March 2002'
>>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month")
'The day is 11, the month is March.'
1.1.4. datetime objects
class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
class methods:
datetime.today()
返回日期时间,结果如下:datetime.datetime(2018, 9, 29, 21, 16, 9, 954626)
datetime.now(tz=None)
返回日期时间,如果tz非空,返回一个tzinfo子类,时间进行转换。
datetime.utcnow() 返回utc时间。
datetime.fromtimestamp(timestamp, ta=None) 根据给出的时间戳返回时日期时间。
datetime.utcfromtimestamp(timestamp) 返回utc日期时间
datetime.fromordinal(ordinal) 返回Gregorian日期时间
datetime.combine(date,time.tzinfo=self.tzinfo) 将date和time对象合并成datetime对象
datetime.strptime(date_string, format) 根据参数,返回datetime对象
class attributes:
datetime.year
datetime.month
datetime.day
datetime.hour
datetime.minute
datetime.second
datetime.microsecond
datetime.tzinfo
datetime.fold
support operations:
|
Operation |
Result |
|
datetime2 = datetime1 + timedelta |
(1) |
|
datetime2 = datetime1 - timedelta |
(2) |
|
timedelta = datetime1 - datetime2 |
(3) |
|
datetime1 < datetime2 |
Compares datetime to datetime. (4) |
instance methods:
date(),time(),timetz(),
replace(year=self.year, month=self.month, day=self.day, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, * fold=0)
astimezone(tz=None)
utcoffset(), dst(),tzname(), timetuple(),utctimetuple()
timestamp()
weekday()
isoweekday()
isocalendar()
isoformat(sep=’T’, timespec=’auto’)
__str__()
ctime()
strftime(format)
__format__(format)
Examples of working with datetime objects:
>>>
>>> from datetime import datetime, date, time
>>> # Using datetime.combine()
>>> d = date(2005, 7, 14)
>>> t = time(12, 30)
>>> datetime.combine(d, t)
datetime.datetime(2005, 7, 14, 12, 30)
>>> # Using datetime.now() or datetime.utcnow()
>>> datetime.now()
datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
>>> datetime.utcnow()
datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
>>> # Using datetime.strptime()
>>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
>>> dt
datetime.datetime(2006, 11, 21, 16, 30)
>>> # Using datetime.timetuple() to get tuple of all attributes
>>> tt = dt.timetuple()
>>> for it in tt:
... print(it)
...
2006 # year
11 # month
21 # day
16 # hour
30 # minute
0 # second
1 # weekday (0 = Monday)
325 # number of days since 1st January
-1 # dst - method tzinfo.dst() returned None
>>> # Date in ISO format
>>> ic = dt.isocalendar()
>>> for it in ic:
... print(it)
...
2006 # ISO year
47 # ISO week
2 # ISO weekday
>>> # Formatting datetime
>>> dt.strftime("%A, %d. %B %Y %I:%M%p")
'Tuesday, 21. November 2006 04:30PM'
>>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time")
'The day is 21, the month is November, the time is 04:30PM.'
Using datetime with tzinfo:
>>>
>>> from datetime import timedelta, datetime, tzinfo
>>> class GMT1(tzinfo):
... def utcoffset(self, dt):
... return timedelta(hours=1) + self.dst(dt)
... def dst(self, dt):
... # DST starts last Sunday in March
... d = datetime(dt.year, 4, 1) # ends last Sunday in October
... self.dston = d - timedelta(days=d.weekday() + 1)
... d = datetime(dt.year, 11, 1)
... self.dstoff = d - timedelta(days=d.weekday() + 1)
... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
... return timedelta(hours=1)
... else:
... return timedelta(0)
... def tzname(self,dt):
... return "GMT +1"
...
>>> class GMT2(tzinfo):
... def utcoffset(self, dt):
... return timedelta(hours=2) + self.dst(dt)
... def dst(self, dt):
... d = datetime(dt.year, 4, 1)
... self.dston = d - timedelta(days=d.weekday() + 1)
... d = datetime(dt.year, 11, 1)
... self.dstoff = d - timedelta(days=d.weekday() + 1)
... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
... return timedelta(hours=1)
... else:
... return timedelta(0)
... def tzname(self,dt):
... return "GMT +2"
...
>>> gmt1 = GMT1()
>>> # Daylight Saving Time
>>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
>>> dt1.dst()
datetime.timedelta(0)
>>> dt1.utcoffset()
datetime.timedelta(0, 3600)
>>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
>>> dt2.dst()
datetime.timedelta(0, 3600)
>>> dt2.utcoffset()
datetime.timedelta(0, 7200)
>>> # Convert datetime to another time zone
>>> dt3 = dt2.astimezone(GMT2())
>>> dt3
datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
>>> dt2
datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
>>> dt2.utctimetuple() == dt3.utctimetuple()
True
1.1.5. time objects
class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
instance attributes(read-only):
hour,minute,second,microsecond,tzinfo,fold
supported operations:
- comparison of time to time.
- hash, use as dict key
- efficent pickling
instance methods:与date,datetime没什么太大不同,不重复了。
1.1.6. strftime() and strptime() behavior
|
Directive |
Meaning |
Example |
|
%a |
Weekday as locale’s abbreviated name. |
Sun, Mon, …, Sat (en_US); So, Mo, …, Sa (de_DE) |
|
%A |
Weekday as locale’s full name. |
Sunday, Monday, …, Saturday (en_US); Sonntag, Montag, …, Samstag (de_DE) |
|
%w |
Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. |
0, 1, …, 6 |
|
%d |
Day of the month as a zero-padded decimal number. |
01, 02, …, 31 |
|
%b |
Month as locale’s abbreviated name. |
Jan, Feb, …, Dec (en_US); Jan, Feb, …, Dez (de_DE) |
|
%B |
Month as locale’s full name. |
January, February, …, December (en_US); Januar, Februar, …, Dezember (de_DE) |
|
%m |
Month as a zero-padded decimal number. |
01, 02, …, 12 |
|
%y |
Year without century as a zero-padded decimal number. |
00, 01, …, 99 |
|
%Y |
Year with century as a decimal number. |
0001, 0002, …, 2013, 2014, …, 9998, 9999 |
|
%H |
Hour (24-hour clock) as a zero-padded decimal number. |
00, 01, …, 23 |
|
%I |
Hour (12-hour clock) as a zero-padded decimal number. |
01, 02, …, 12 |
|
%p |
Locale’s equivalent of either AM or PM. |
AM, PM (en_US); am, pm (de_DE) |
|
%M |
Minute as a zero-padded decimal number. |
00, 01, …, 59 |
|
%S |
Second as a zero-padded decimal number. |
00, 01, …, 59 |
|
%f |
Microsecond as a decimal number, zero-padded on the left. |
000000, 000001, …, 999999 |
|
%z |
UTC offset in the form +HHMM or -HHMM (empty string if the object is naive). |
(empty), +0000, -0400, +1030 |
|
%Z |
Time zone name (empty string if the object is naive). |
(empty), UTC, EST, CST |
|
%j |
Day of the year as a zero-padded decimal number. |
001, 002, …, 366 |
|
%U |
Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. |
00, 01, …, 53 |
|
%W |
Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0. |
00, 01, …, 53 |
|
%c |
Locale’s appropriate date and time representation. |
Tue Aug 16 21:30:00 1988 (en_US); Di 16 Aug 21:30:00 1988 (de_DE) |
|
%x |
Locale’s appropriate date representation. |
08/16/88 (None); 08/16/1988 (en_US); 16.08.1988 (de_DE) |
|
%X |
Locale’s appropriate time representation. |
21:30:00 (en_US); 21:30:00 (de_DE) |
|
%% |
A literal '%' character. |
% |
笔记-python-standard library-8.1 data types-datetime的更多相关文章
- Python Standard Library
Python Standard Library "We'd like to pretend that 'Fredrik' is a role, but even hundreds of vo ...
- The Python Standard Library
The Python Standard Library¶ While The Python Language Reference describes the exact syntax and sema ...
- Python语言中对于json数据的编解码——Usage of json a Python standard library
一.概述 1.1 关于JSON数据格式 JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 46 ...
- 《The Python Standard Library》——http模块阅读笔记1
官方文档:https://docs.python.org/3.5/library/http.html 偷个懒,截图如下: 即,http客户端编程一般用urllib.request库(主要用于“在这复杂 ...
- 《The Python Standard Library》——http模块阅读笔记2
http.server是用来构建HTTP服务器(web服务器)的模块,定义了许多相关的类. 创建及运行服务器的代码一般为: def run(server_class=HTTPServer, handl ...
- 《The Python Standard Library》——http模块阅读笔记3
http.cookies — HTTP state management http.cookies模块定义了一系列类来抽象cookies这个概念,一个HTTP状态管理机制.该模块支持string-on ...
- Python Standard Library 学习(一) -- Built-in Functions 内建函数
内建函数列表 Built-in Functions abs() divmod() input() open() staticmethod() all() enumerate() int() ord() ...
- 【12c】扩展数据类型(Extended Data Types)-- MAX_STRING_SIZE
[12c]扩展数据类型(Extended Data Types)-- MAX_STRING_SIZE 在12c中,与早期版本相比,诸如VARCHAR2, NAVARCHAR2以及 RAW这些数据类型的 ...
- Data Types in the Kernel <LDD3 学习笔记>
Data Types in the Kernel Use of Standard C Types /* * datasize.c -- print the size of common data it ...
- C++11新特性——The C++ standard library, 2nd Edition 笔记(一)
前言 这是我阅读<The C++ standard library, 2nd Edition>所做读书笔记的第一篇.这个系列基本上会以一章一篇的节奏来写,少数以C++03为主的章节会和其它 ...
随机推荐
- 初识MAC(由window到mac的转变适应)
* Windows上的软件可以拿到Mac上面安装吗? Windows上面的软件不能拿到Mac的操作系统上安装,除此之外,Windows里的 exe文件,在Mac下面也是无法运行的,要特別注意.如果你要 ...
- 【干货】JavaScript DOM编程艺术学习笔记7-9
七.动态创建标记 在文档中不写占位图片和文字代码,在能调用js的情况下动态创建,文档支持性更好. 在原来的addLoadEvent prepareGallery showPic的基础上增加函数prep ...
- 修改Oracle环境变量$PATH
此次在创建公司的Oracle 标准化应用时,提到了添加$PATH,但没有发现对我很符合我的现况的方法,现记录下此次添加$PATH的方法: 首先查看$PATH中是否已存在我们需要的路径: 执行指令ech ...
- WPF:鼠标长时间无操作,窗口隐藏
//设置鼠标长时间无操作计时器 private System.Timers.Timer MouseTimerTick = new System.Timers.Timer(10000); private ...
- TFS看板规则
就绪板列 准入条件 需求已完成交付 需求交付过程中的问题已全部解决 当前迭代需求所产生的BUG必须放入该列 之前迭代遗留的BUG 工作内容 需求实现概要设计 BUG确认 任务拆分 任务工作量估算(单位 ...
- Extjs4.1+desktop+SSH2 搭建环境 项目能跑起来
linux开发感觉可能就是日常办公的时候,用别的软件会有问题,java开发还是没什么区别的,换回window开发: push 它: 每次看到右上那红红的叉,我还以为又出错了: 这个项目用resin,下 ...
- [转载]AngularJS快速开始
AngularJS快速开始 Hello World! 开始学习AngularJS的一个好方法是创建经典应用程序“Hello World!”: 使用您喜爱的文本编辑器,创建一个HTML文件,例如:hel ...
- HTTP 请求方法介绍
浏览器从 web 服务器(或者叫应用服务器)上使用 HTTP 协议下载网站,HTTP 协议是基于一种 请求-响应(request-response)模型的.客户端(你的浏览器)从运行在物理机器上的 w ...
- dom事件操作例题,电子时钟,验证码,随机事件
dom事件操作 当事件发生时,可以执行js 例子: 当用户点击时,会改变<h1>的内容: <h1 onClick="this.innerHTML='文本更换'"& ...
- winform下读取excel文件并绑定datagridview例子
首先我要读取这个excel文件然后生成Datable 用winform编程的方式 前台界面: 后台的代码 using System; using System.Collections.Generic; ...