python中datetime模块解析

440 阅读5分钟

python中datetime模块解析

python中的datetime是一个模块,下面有datetime、date、time、timedelta三个类,很多人把datetime和datetime.datetime搞混了,实际上datetim是模块,datetime.datetime是类

date类

import datetime

# 创建date对象, 年月日
date_obj = datetime.date(2021, 2, 12)

date类方法

1.today()

2.fromtimestamp()

3.fromordinal()

4.fromisoformat()

5.fromisocalendar()

date类属性

min|max|resolution

date实例属性

date实例方法

有时间再更新。

time类

calendar类

有时间再更新。

datetime类

datetime 模块中的常用类即date、datetime、time、timedelta、timezone、tzinfo。

import datetime

# 创建datetime对象, 时分秒
datetime_obj = datetime.datetime(2021, 2, 12, 15, 12, 11)

构造一个datetime.datetime实例

datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

datetime类方法

1.today()

返回一个当前时间的datetime对象

2.now()

返回一个当前时间的datetime对象

td = datetime.datetime.today()
print(td) # 2022-07-11 22:18:44.519811
print(td.year) # 2022
print(type(td)) # <class 'datetime.datetime'>

n = datetime.datetime.now()
print(n) # 2022-07-11 22:18:44.519811
print(n.year) # 2022
print(type(n)) # <class 'datetime.datetime'>

3.fromtimestamp()

时间戳表示为本地时间的简单日期时间对象, 如果可选参数 tz 为 None 或未指定,时间戳会被转换为所在平台的本地日期和时间,返回的 datetime 对象将为天真型

4.fromordinal()

返回对应于预期格列高利历序号的 datetime,其中公元 1 年 1 月 1 日的序号为 1。 除非 1 <= ordinal <= datetime.max.toordinal() 否则会引发 ValueError。结果的 hour, minute, second 和 microsecond 值均为 0,并且 tzinfo 值为 None。

5.combine()

返回一个date对象和一个time对象合成的datetime对象, 如果提供了 tzinfo 参数,其值会被用来设置结果的 tzinfo 属性,否则将使用 time 参数的 tzinfo 属性。

6.fromisoformat()

将满足条件: (YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]],其中 * 可以匹配任意的单个字符)的字符串转化为datetime.datetime对象。

7.fromisocalendar()

接收三个参数year,week,day,即返回固定年份year的第week周的第day天的日期对象。

8.strptime()

按照指定的时间格式将字符串时间转化为datetime.datetime对象

import datetime

# fromtimestamp()
print(datetime.datetime.fromtimestamp(1))  # 1970-01-01 08:00:01

# fromordinal()
print(datetime.datetime.fromordinal(730920)) # 2002-03-11 00:00:00
print(datetime.datetime.fromordinal(1)) # 0001-01-01 00:00:00

# combine
d = datetime.date(2021, 6, 26)
t = datetime.time(12, 30)
print(datetime.datetime.combine(d, t)) # 2021-06-26 12:30:00
print(type(datetime.datetime.combine(d, t))) # <class 'datetime.datetime'>

# fromisoformat
print(datetime.datetime.fromisoformat('2019-12-04')) # 2019-12-04 00:00:00
print(datetime.datetime.fromisoformat('2019-11-04K12:24:21.123')) # 2019-11-04 12:24:21.123000
print(datetime.datetime.fromisoformat('2019-11-04K12:24:21+02:23')) # 2019-11-04 12:24:21+02:23

# fromisocalendar()
print(datetime.datetime.fromisocalendar(2000, 12, 1)) # 2000-03-20 00:00:00
print(datetime.datetime.fromisocalendar(2022, 28, 2)) # 2022-07-12 00:00:00

# strptime(date_string=None, format=None)
print(datetime.datetime.strptime("21/11/21 16:30", "%d/%m/%y %H:%M")) # 2021-11-21 16:30:00

datetime类属性

min、max、resolution

print(datetime.datetime.resolution) # 0:00:00.000001,最小时间间隔
print(datetime.datetime.max) # 9999-12-31 23:59:59.999999
print(datetime.datetime.min) # 0001-01-01 00:00:00

datetime实例方法

1.date()

返回一个和实例有一样的日期信息的datetime.date类

dt = datetime.datetime(2022, 7, 13, 9, 12, 11)
print(dt.date()) # 2022-07-13
print(type(dt.date())) # <class 'datetime.date'>

2.time()

返回一个和实例有一样的时间信息的datetime.time类

dt = datetime.datetime(2022, 7, 13, 9, 12, 11)
print(dt.time()) # 09:12:11
print(type(dt.time())) # <class 'datetime.time'>

3.astimezone()

返回一个新时区的datetime.datetime对象。

dt = datetime.datetime.now()
import pytz
print(dt.astimezone(tz=pytz.timezone('US/Eastern')))
print(dt.astimezone(tz=pytz.timezone('Asia/Tokyo')))
print(dt.astimezone(tz=pytz.timezone('Asia/Shanghai')))

4.replace()

根据用户指定的新值(未指定的则继承实例的属性),返回一个新的datetime.datetime对象

# 函数原型
def replace(self, year=None, month=None, day=None, hour=None,
            minute=None, second=None, microsecond=None, tzinfo=True,
            *, fold=None)

# test
dt = datetime.datetime(2022, 7, 13, 9, 12, 11)
print(dt.replace(year=2021, month=2)) # 2021-02-13 09:12:11

5.timetuple()

返回一个time.struct_time,和time.localtime()所返回的类型相同

dt = datetime.datetime(2022, 7, 13, 9, 12, 11)
print(dt.timetuple()) # time.struct_time(tm_year=2022, tm_mon=7, tm_mday=13, tm_hour=9, tm_min=12, tm_sec=11, tm_wday=2, tm_yday=194, tm_isdst=-1)
import time
print(time.localtime()) # time.struct_time(tm_year=2022, tm_mon=7, tm_mday=13, tm_hour=10, tm_min=8, tm_sec=17, tm_wday=2, tm_yday=194, tm_isdst=0)

6.toordinal()

返回实例日期的预期格列高利历序号,是fromordinal的逆操作

7.timestamp()

返回对应于 datetime 实例的时间戳,与 time.time() 返回值类似的 float 对象。

8.weekday()

返回当前日期是一周的第几天(0-周一, 6-周日)

9.isoweekday()

返回一个整数代表周几,和weekday()类似,1-周一, 7-周日

10.isocalendar()

返回一个元组(year, week, weekday)分别代表年、第几周、周几

11.isoformat()

返回实例时间的日期字符串,datetime.isoformat(sep='T', timespec='auto')

12.strftime()

将日期转化为给定格式的字符串

dt = datetime.datetime(2022, 7, 13, 9, 12, 11)
print(dt.weekday())  # 2
print(dt.isoweekday())  # 3

t = dt.isocalendar()
print(t)  # datetime.IsoCalendarDate(year=2022, week=28, weekday=3)
print(t[0], t[1], t[2])  # 2022 28 3

print(dt.isoformat(sep='T'))  # 2022-07-13T09:12:11

print(dt.strftime("%Y-%m-%d %H:%M:%S"))  # 2022-07-13 09:12:11
print(dt.strftime("%y-%m-%d %H:%M"))  # 22-07-13 09:12

datetime实例属性

year|month|day|hour|minute|second|microsecond

dt = datetime.datetime(2022, 7, 13, 8, 12, 11)
print(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second) # 2022 7 13 8 12 11

pandas中时间模块

时间戳转换

需要使用pandas.to_datetime()函数,参数说明:

pd.to_datetime(
    arg, # int, float, str, datetime, list, tuple, 1-d array, Series DataFrame/dict-like
    errors='raise',# {'ignore', 'raise', 'coerce'}, default 'raise'
    dayfirst=False,
    yearfirst=False,
    utc=None,
    format=None,# 格式,比如 "%d/%m/%Y"
    exact=True,
    unit=None,# 单位str, default 'ns',可以是(D,s,ms,us,ns)
    infer_datetime_format=False,
    origin='unix',# 指定从什么时间开始,默认为19700101
    cache=True,
)

实例代码:

import pandas as pd

# 如果原来的数据是以时间戳(秒、毫秒、纳秒), 需要指定unit参数
df['time'] = pd.to_datetime(df['time_stamps'], unit='s',origin=pd.Timestamp('2018-07-01'))

# 如果原来的数据是字符串类型的规范化时间数据, 需要指定fromat参数
df['time'] = pd.to_datetime(df['time_str'], format='%Y-%m-%d %H:%M:%S')

将time_stamps这列的时间戳转换为日期格式,单位是秒(unit='s'),还可以指定毫秒(ms)、纳秒(ns),计算的日期是从2018年的7月1号开始,即从2018年的7月1号开始加上时间戳的那么多秒。

参数fromat, 正确使用可以大大加快转换的速度:# %Y:四位数年份,%m:月份,%d:日期,%H:小时,%M:分钟,%S:秒。