python datetime模块

简介: python datetime模块

引入模块

import datetime

datetime模块提供了五个常用类:date、time、datetime、timedelta、tzinfo,接下来我们对这五个常用类进行说明。


date类

date类包含三个参数,分别为year,month,day,返回格式为year-month-day。

date对象表示理想化日历中的日期(年、月和日), 公历1年1月1日被称为第一天,依次往后推。

其中用户创建时间的类方法如下:

import datetime
print("今天的日期是:",datetime.date.today())     # 今日的日期
print("使用时间戳创建的日期:",datetime.date.fromtimestamp(1234567896))   #  使用时间戳创建日期
print("使用公历序数创建的日期:",datetime.date.fromordinal(1))    # 使用公历序数创建的日期
返回内容:
今天的日期是: 2023-03-12
使用时间戳创建的日期: 2009-02-14
使用公历序数创建的日期: 0001-01-01

对象的属性及方法如下:

import datetime
today = datetime.date(year=2023,month=3,day=12)   #  使用参数创建日期
print('date对象的年份:', today.year)
print('date对象的月份:', today.month)
print('date对象的日:', today.day)
print("date对象的struct_time结构为:",today.timetuple())
print("返回当前公历日期的序数:",today.toordinal())   #  与fromordinal函数作用相反
print("当前日期为星期(其中:周一对应0):{}".format(today.weekday()))
print("当前日期为星期(其中:周一对应1):{}".format(today.isoweekday()))
print("当前日期的年份、第几周、周几(其中返回为元组):",today.isocalendar())
print("以ISO 8601格式‘YYYY-MM-DD’返回date的字符串形式:",today.isoformat())
print("返回一个表示日期的字符串(其格式如:Sun Mar 12 00:00:00 2023):",today.ctime())
print("指定格式为:",today.strftime("%Y/%m/%d"))
print("替换后的日期为:",today.replace(2021,4,26))
返回内容:
date对象的年份: 2023
date对象的月份: 3
date对象的日: 12
date对象的struct_time结构为: time.struct_time(tm_year=2023, tm_mon=3, tm_mday=12, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=71, tm_isdst=-1)
返回当前公历日期的序数: 738591
当前日期为星期(其中:周一对应0):6
当前日期为星期(其中:周一对应1):7
当前日期的年份、第几周、周几(其中返回为元组): (2023, 10, 7)
以ISO 8601格式‘YYYY-MM-DD’返回date的字符串形式: 2023-03-12
返回一个表示日期的字符串(其格式如:Mon Aug 31 00:00:00 2020): Sun Mar 12 00:00:00 2023
指定格式为: 2023/03/12 

格式化表达式:

%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31)
%H 24小时制小时数(0-23)
%I 12小时制小时数(01-12)
%M 分钟数(00=59)
%S 秒(00-59)
%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%f 微秒 (000001-999999)
%j 年内的一天(001-366)
%p 本地A.M.或P.M.的等价符
%U 一年中的星期数(00-53)星期天为星期的开始
%w 星期(0-6),星期天为星期的开始
%W 一年中的星期数(00-53)星期一为星期的开始
%x 本地相应的日期表示
%X 本地相应的时间表示
%Z 当前时区的名称
%% %号本身 

time类

time类包含六个参数,分别为hour,minute,second,microsecond,tzinfo,fold,返回格式为hour:minute:second(.microsecond)。常用的参数有:hour、minute、second三个。

其对象的属性和方法如下:  

import datetime
create_time = datetime.time(hour=11,minute=18,second=31)   #  使用参数创建日期
print('create_time对象的小时为:', create_time.hour)
print('create_time对象的分钟为:', create_time.minute)
print('create_time对象的秒数为:', create_time.second) 
print("返回create_time的字符串形式:",create_time.isoformat())
print("指定格式为:",create_time.strftime("%H/%M/%S"))
print("替换后的时间为:",create_time.replace(20,9,29))
内容如下:
create_time对象的小时为: 11
create_time对象的分钟为: 18
create_time对象的秒数为: 31
返回create_time的字符串形式: 11:18:31
指定格式为: 11/18/31
替换后的时间为: 20:09:29 

datetime类

datetime类可以看作date和time类的合体,其包含了这两个类中的全部参数,其中创建datetime类的类方法如下:

import datetime
print("现在的时间是:",datetime.datetime.today())
print("返回现在的时间是:",datetime.datetime.now())
print("当前UTC日期和时间是:",datetime.datetime.utcnow())
print("对应时间戳的日期和时间是:",datetime.datetime.fromtimestamp(1234567896))
print("对应UTC时间戳的日期和时间是:",datetime.datetime.utcfromtimestamp(1234567896))
print("公历序列对应的日期和时间是:",datetime.datetime.fromordinal(1))
print("日期和时间的合体为:",datetime.datetime.combine(datetime.date(2023, 3, 12), datetime.time(21, 12, 12)))
返回内容:
现在的时间是: 2023-03-12 21:41:56.971984
返回现在的时间是: 2023-03-12 21:41:56.971983
当前UTC日期和时间是: 2023-03-12 13:41:56.971983
对应时间戳的日期和时间是: 2009-02-14 07:31:36
对应UTC时间戳的日期和时间是: 2009-02-13 23:31:36
公历序列对应的日期和时间是: 0001-01-01 00:00:00
日期和时间的合体为: 2023-03-12 21:12:12 

对象的属性和方法如下:

import datetime
now = datetime.datetime(2023,3,12,21,44,10)
print("年为:",now.year)
print("月为:",now.month)
print("日为:",now.day)
print("小时为:",now.hour)
print("分钟为:",now.minute)
print("秒数为:",now.second)
print('当前日期为:', now.date() )
print('当前时间:', now.time() )
print("返回struct_time为",now.timetuple())   #  和date一样
print("返回UTC的struct_time为",now.utctimetuple())
print("返回的公历序列数为:",now.toordinal())   #  和date一样
print("返回标准日期格式为:",now.isoformat())   #  和date一样
print("返回的周几(1表示周一):",now.isoweekday())    #  和date一样
print("返回的周几(0表示周一):",now.weekday())    #  和date一样
print("now.isocalendar():", now.isocalendar())  #  和date一样
print("now.ctime():",now.ctime())   #  和date一样
print("格式化时间为:",now.strftime('%Y/%m/%d %H:%M:%S'))   #  把日期按照format指定的格式进行格式化
print(datetime.datetime.strptime("2023/3/12 21:44:00",'%Y/%m/%d %H:%M:%S'))     #   将字符串格式转换为日期格式
返回内容:
年为: 2023
月为: 3
日为: 12
小时为: 21
分钟为: 44
秒数为: 10
当前日期为: 2023-03-12
当前时间: 21:44:10
返回struct_time为 time.struct_time(tm_year=2023, tm_mon=3, tm_mday=12, tm_hour=21, tm_min=44, tm_sec=10, tm_wday=6, tm_yday=71, tm_isdst=-1)
返回UTC的struct_time为 time.struct_time(tm_year=2023, tm_mon=3, tm_mday=12, tm_hour=21, tm_min=44, tm_sec=10, tm_wday=6, tm_yday=71, tm_isdst=0)
返回的公历序列数为: 738591
返回标准日期格式为: 2023-03-12T21:44:10
返回的周几(1表示周一): 7
返回的周几(0表示周一): 6
now.isocalendar(): (2023, 10, 7)
now.ctime(): Sun Mar 12 21:44:10 2023
格式化时间为: 2023/03/12 21:44:10
2023-03-12 21:44:00

timedelta类

timedelta类代表两个datetime对象之间的时间差,即两个日期或者日期时间之差。支持参数:weeks、days、hours、minutes、seconds、milliseconds、microseconds。但是据官方文档说其内部只存储days、seconds 和 microseconds,其他单位会做对应的时间转换。

import datetime
now = datetime.date.today()
before_5_date = now + datetime.timedelta(days=-5)
print("now date is:",now)   # 表示现在的日期
print("before five days date is:",before_5_date)   # 表示五天前的日期
now_time = datetime.datetime.now()
print(now_time)
after_5_hours_10_minutes = now_time + datetime.timedelta(hours=5,minutes=10)
print(after_5_hours_10_minutes)
返回内容:
now date is: 2023-03-12
before five days date is: 2023-03-07
2023-03-12 21:48:32.697045
2023-03-13 02:58:32.697045

tzinfo类

tzinfo类是一个虚拟基类,代表时区(time zone),创建子类时必须重写name(),utcoffset(),dst()这三个方法,tzinfo类在日常工作中用的比极少。

import datetime
#tzinfo查看utc_time属性
utc_time = datetime.datetime.utcnow()
print(utc_time)
print(utc_time.tzinfo)
2023-03-12 14:19:27.963555
None 


时间转换

time.localtime() 本地当前时间

time.time 1970到现在的时间

time实现当前时间转换为时间戳

strptime要求传入的t为string类型,可以用到str()方法进行转换,mktime要求处理tuple类型  

方式一
import time
t = '2023-3-12 00:00:00'
s_t = time.strptime(t, "%Y-%m-%d %H:%M:%S")  # 返回元祖
print(type(s_t))
print(s_t)
mkt = int(time.mktime(s_t))
print(mkt)  
<class 'time.struct_time'>
time.struct_time(tm_year=2023, tm_mon=3, tm_mday=12, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=71, tm_isdst=-1)
1678550400
方式二
import datetime
import time
d_time = datetime.datetime.now()
un_time = time.mktime(d_time.timetuple())
print(un_time)
将unix时间戳转换为“当前时间”格式
times = datetime.datetime.fromtimestamp(un_time)
print(times)
1678629533.0
2023-03-12 21:58:53

string和datetime互转

string to datetime

import datetime
str = '2023-3-12'
date_time = datetime.datetime.strptime(str,'%Y-%m-%d')
print(type(date_time))
<class 'datetime.datetime'>

datetime to string

import datetime
# # 获得当前时间
now_date = datetime.datetime.now()
print(type(now_date))
str_date = now_date.strftime("%Y-%m-%dT%H:%M:%S.%f")
print(type(str_date))
<class 'datetime.datetime'>
<class 'str'>  

timezone和timedelta时区

from datetime import timezone, timedelta
beijing = timezone(timedelta(hours=8))
print(f'1、北京时区为:{beijing}')
Tokyo = timezone(timedelta(hours=9))
print(f'2、东京时区为:{Tokyo}')
New_York = timezone(timedelta(hours=-4))
print(f'3、纽约时区为:{New_York}')
utc = timezone.utc
print(f'4、世界标准时区为:{utc}')
北京时区为:UTC+08:00
东京时区为:UTC+09:00
纽约时区为:UTC-04:00
世界标准时区为:UTC

获取当前时间简单介绍

方法一
now_date获取当前本机时间,format为2023-03-12 21:14:20.328375,type为datetime.datetime,本机是北京时间,东八区,世界标准时间相差八小时,需要用到timedelta对datetime.datetime进行加减计算,strftime将datetime.datetime类型转换为指定的string类型,根据需求进行切割和拼接。
方法二
datetime.datetime.now()后,astimezone(datetime.timezone.utc)输出世界标准时间
方法三
datetime.datetime.utcnow() 直接输出世界标准时间  

demo

根据当前时间获取世界标准时间,并输出为下面格式:2023-03-12T13:11:10.702Z  

方法一:

import datetime
# # 获得当前时间
now_date = datetime.datetime.now()
datetime_date = now_date-datetime.timedelta(hours=8)
str_date = datetime_date.strftime("%Y-%m-%dT%H:%M:%S.%f")
three_ms = str_date[:-3]+"Z"
print(three_ms)

方法二:

import datetime
now = datetime.datetime.now()
utc_time = now.astimezone(datetime.timezone.utc)
utc_time_str = utc_time.strftime('%Y-%m-%dT%H:%M:%S.%f')
utc_time_str_1 = utc_time_str[:-3]+"Z"
print(utc_time_str_1)  

方法三

import datetime
now = datetime.datetime.utcnow()
utc_time_str_2 = now.strftime('%Y-%m-%dT%H:%M:%S.%f')
utc_time_str_3 = utc_time_str_2[:-3]+"Z"
print(utc_time_str_3)


目录
相关文章
|
2天前
|
Python
【Python进阶(五)】——模块搜索及工作目录
【Python进阶(五)】——模块搜索及工作目录
|
17天前
|
机器学习/深度学习 存储 Python
|
1天前
|
Python
在Python中,利用`os模块`的`path.exists()`函数可判断文件是否存
在Python中,利用`os模块`的`path.exists()`函数可判断文件是否存在,该函数对路径进行检查,存在则返回True,不存在则返回False。示例代码展示了如何检查&#39;example.txt&#39;文件是否存在并相应打印消息。此外,`os.path.isfile()`用于确认路径是否为文件,仅当是文件时返回True,否则返回False,同样配以示例说明其用法。
8 2
|
4天前
|
Python Windows
python中的异常与模块
python中的异常与模块
10 1
|
13天前
|
JSON 数据格式 Python
Python标准库中包含了json模块,可以帮助你轻松处理JSON数据
【4月更文挑战第30天】Python的json模块简化了JSON数据与Python对象之间的转换。使用`json.dumps()`可将字典转为JSON字符串,如`{&quot;name&quot;: &quot;John&quot;, &quot;age&quot;: 30, &quot;city&quot;: &quot;New York&quot;}`,而`json.loads()`则能将JSON字符串转回字典。通过`json.load()`从文件读取JSON数据,`json.dump()`则用于将数据写入文件。
17 1
|
14天前
|
Python
Python实现压缩解压---tarfile模块详解
Python实现压缩解压---tarfile模块详解
|
14天前
|
Linux Python Windows
Python中time和datetime模块详解
Python中time和datetime模块详解
|
15天前
|
存储 Linux 数据安全/隐私保护
python的压缩模块zipfile详解
python的压缩模块zipfile详解
|
15天前
|
Linux Python Windows
python的os模块详细解读(二)
python的os模块详细解读(二)
|
15天前
|
移动开发 Linux Shell
python的os模块详细解读(一)
python的os模块详细解读(一)
python的os模块详细解读(一)