Python 中使用日期时间数据的 3 个强大技巧

Python 中使用日期时间数据的 3 个强大技巧

了解如何使用日期时间模块。日期时间数据是您将使用的最常见且最耗时的数据类型之一。

无论是执行时间序列分析、为机器学习模型准备数据,还是仅执行探索性数据分析,都需要使用数据中存在的此类日期时间值。

此外,当您合并来自多个源的数据时,日期时间数据以不同的格式显示。为了保持数据一致性,您需要将所有日期时间值转换为单一/标准格式,因此您必须了解这些技术才能使用它们。

您必须至少花费五分钟来搜索如何操作此类日期时间数据。每次使用此类日期时间数据时也是如此。我总是花时间在这上面!!

因此,在本文中,我将分享 3 个在 Python 中处理日期时间数据的快速技巧,您可以使用它们完成大部分日期时间数据处理。我建议保存这个故事,以便将来快速参考。

在 Python 中,您可以使用各种模块,例如日历、 和时间。尽管每个模块在不同的场景中都很有用,但我发现该模块用途广泛,因为它提供了同时使用日期和时间的方法:datetime.datetime

因此,在这里您将了解有关此模块以及如何有效地使用其方法来转换日期时间数据的更多信息。datetime

您可以在阅读结束时下载包含所有这些示例和其他资源的完整笔记本!

在开始介绍提示和技巧之前,让我们快速回顾一下从模块获取的日期时间值的外观。datetime

您始终使用模块中的类获取当前日期和时间,如下所示:

from datetime import datetime
current_time = datetime.now()
current_time

# Output
datetime.datetime(2023, 7, 8, 19, 40, 6, 832421)

好吧,您可以看到输出看起来不像日期,而只是看起来像一组值。但是,为什么会这样呢?

因为该函数返回一个对象。所以,是一个对象。

datetime.now() datetimedatetime.datetime(2023, 7, 8, 19, 40, 6, 832421)

datetime

前 3 个数字分别表示年、月和日。接下来的 3 个数字分别表示小时、分钟和秒的时间。而最后一个数字表示毫秒。

您可以通过简单地打印current_time进行交叉检查,如下所示。

print(current_time)

# Output
2023-07-08 19:40:06.832421

您可以看到,来自对象的值现在以易于理解的格式排列。datetime

现在,当您探索基础知识时,让我们继续学习 3 个技巧,以便在 Python 中轻松处理此类日期时间值。

在实际数据集中,日期和时间值并不总是存在于数据类型中,而是作为字符串提及。因此,若要使用这些值,首先需要将这些字符串转换为对象。datetimedatetime

Python 中的模块提供了两种非常有用的方法 - 和 - 将字符串转换为日期时间值,反之亦然。

datetime.strptime()

如何使用 strftime() 和 strptime()

根据这两种方法处理日期时间字符串或日期时间值的方式,这两种方法之间存在微小但显着的差异。为了有效地使用它们,您需要了解它们之间的区别。

该方法本质上是“解析字符串”,即它将日期时间字符串作为输入,并返回日期时间值或对象作为输出。strptime()datetime

然而,该方法本质上是“格式化字符串”,即它将日期时间值作为输入,并以指定格式返回日期时间字符串作为输出。strftime()

让我们使用以下示例来了解这种差异,您将首先使用该方法将日期时间字符串转换为对象。然后,您将使用将此对象转换回原始日期时间字符串。strptime()datetimestrftime()

current_time_string = '2023-07-08 19:40:06' strptime_output = datetime.strptime(current_time_string, "%Y-%m-%d %H:%M:%S") strptime_output

Output

datetime.datetime(2023, 7, 8, 19, 40, 6) 您可以快速检查此方法的输入和输出的数据类型,如下所示。strptime()

print(f"Data type of current_time_string: {type(current_time_string)}") print(f"Data type of strptime_output: {type(strptime_output)}")

Output

Data type of current_time_string: <class 'str'> Data type of strptime_output: <class 'datetime.datetime'> 同样,要了解该方法的工作原理,您只需将上述代码中创建的日期时间对象传递给 并将其转换回字符串。strftime()strftime()

让我告诉你如何——

strftime_output = datetime.strftime(strptime_output, "%Y-%m-%d %H:%M:%S") strftime_output

Output

'2023-07-08 19:40:06' 如果你现在检查strftime_output和current_time_string的数据类型,你会发现它是相同的——<class ‘str’>

总之

strptime() — 将日期时间字符串转换为日期时间对象

strftime() — 将日期时间对象转换为日期时间字符串

但是,如果您使用的是 pandas 数据帧,则只需使用 pandas 方法将日期时间字符串转换为时间戳即可。要了解更多信息,请查看以下文章。to_datetime()

使用日期时间数据的 3 个有用的熊猫技巧 快速了解如何转换时间序列数据并在 Python Pandas 中获取大部分数据

了解这两种方法之间的区别后,可以探索不同的字符串格式类型以获取不同形式的日期,如下所示。

#1 指定了年月和日的位置
datetime.strftime(strptime_output, "%Y-%d-%m %H:%M:%S")
##1 Output
'2023-08-07 19:40:06'

#2 只获取年份后两位数字
datetime.strftime(strptime_output, "%y-%m-%d %H:%M:%S")
##2 Output
'23-07-08 19:40:06'

#3 用月份的英文写法替代月份数字
datetime.strftime(strptime_output, "%Y-%h-%d %H:%M:%S")
##3 Output
'23-Jul-08 19:40:06'

这样,通过更改日期时间字符串中字母表的顺序和大小写,您可以通过多种方式格式化输出:%Y-%m-%d%H:%M:%S

通常,您不需要整个日期时间值或字符串,而只需要其中的一部分,例如仅日、月或年。因此,让我们探讨如何从日期时间字符串中获取它们。

如何在 Python 中提取年、月、日、小时、分钟、秒从日期开始 您可能已经注意到,当您更改中提到的日期时间字符串中的字母表时,您会得到不同的输出。strftime()

您可以使用完全相同的逻辑获取日期时间字符串的不同部分。

例如,您不希望日期时间字符串中的所有值都显示日期部分,而是希望仅查看字符串格式的日期部分

您需要做的就是在如下所示中提及:DD/MM/YY%Dstrftime()

strptime_output = datetime(2023, 7, 8, 19, 40, 6)
datetime.strftime(strptime_output, "%D")

# Output
'07/08/23'

同样,从日期时间字符串中提取年、月、日、小时、分钟和秒, 如下所示:

# Get Year
datetime.strftime(strptime_output, "%Y")
## Output
'2023'

# Get the Month number
datetime.strftime(strptime_output, "%m")
## Output
'07'

# Get the day of month
datetime.strftime(strptime_output, "%d")
## Output
'08'

# Get the Hour of day
datetime.strftime(strptime_output, "%H")
## Output
'19'

# Get the Minute
datetime.strftime(strptime_output, "%M")
## Output
'40'

# Get the Second
datetime.strftime(strptime_output, "%S")
## Output
'06'

%”%m 返回的年月日等数字。

但是,有时仅月数或月中的日数是不够的。您需要月份的名称或工作日的名称。您可以使用字符串格式的其他字母获取此类信息,如下所示。


# Get the Month name
datetime.strftime(strptime_output, "%B")
## Output
'July'

# Get the Month name (in short)
datetime.strftime(strptime_output, "%b")
## Output
'Jul'

# Get the day name
datetime.strftime(strptime_output, "%A")
## Output
'Saturday'

# Get the day name (in short)
datetime.strftime(strptime_output, "%a")
## Output
'Sat'

# Get the Date in YYYY-DD-MM format
datetime.strftime(strptime_output, "%F")
## Output
'2023-07-08'

同样,当您提取上面的日期部分时,您只能从日期时间字符串中提取 24 小时格式的时间部分,甚至可以通过以下方式提取格式。HH:MM:SSHH:MM

# Get the Time in HH:MM:SS format
datetime.strftime(strptime_output, "%T")
## Output
'19:40:06'

# Get the Time in HH:MM format
datetime.strftime(strptime_output, "%R")
## Output
'19:40'

此外,您可以使用字符串格式了解有关一天中时间的更多信息——无论是在中午 12 点之前还是下午 12 点之后,如下所示:%p

# Get the time of day (AM or PM)
datetime.strftime(strptime_output, "%p")
## Output
'PM'

# Get the complete time of day (HH:MM:SS AM or HH:MM:SS PM)
datetime.strftime(strptime_output, "%r")
## Output
'07:40:06 PM'

# Get the time of day (AM or PM)
datetime.strftime(datetime(2023, 7, 8, 9, 40, 6), "%p")
## Output
'AM'

# Get the complete time of day (HH:MM:SS AM or HH:MM:SS PM)
datetime.strftime(datetime(2023, 7, 8, 9, 40, 6), "%r")
## Output
'09:40:06 AM'

我知道很难记住所有这些,这就是为什么我说,你可以收藏或保存这个故事以供快速参考,因为我已经这样做了。

在上述所有方法中,有一件事是共同的 — 输出是字符串形式 — 因为您每次都使用该方法。strftime()

但是,如果您想以非字符串格式获取这些日期部分怎么办?

您也可以获取数据类型中的日期部分。这也直接来自对象。

好记!

strptime_output = datetime(2023, 7, 8, 19, 40, 6)

# Get Year
strptime_output.year
## Output
2023

# Get the Month number
strptime_output.month
## Output
7

# Get the day of month
strptime_output.day
## Output
8

# Get the Hour of day
strptime_output.hour
## Output
19

# Get the Minute
strptime_output.minute
## Output
40

# Get the Second
strptime_output.second
## Output
6

您对日期作增减的操作,还可以从此对象中仅获取数据类型中的日期或时间部分,如下所示:

# Get Date
strptime_output.date()
## Output
datetime.date(2023, 7, 8)

# Get Time
strptime_output.time()
## Output
datetime.time(19, 40, 6)

一旦你得到了这样的日期部分,下一个重要的事情就是操纵日期——从日期或时间中添加或减去这些日期部分。

如何在 Python 中添加或减去日期和时间

当您从日期或时间中添加或减去日期部分或时间部分时,您实际上是在处理持续时间,即两个对象之间的差异。

在 Python 中,持续时间由timedelt模块中的类处理。

要向对象添加日期部分或时间部分,您必须具有另一个对象,并且此需求由对象满足。它具有非常简单的语法,如下所示:timedelta()

from datetime import timedelta
timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

所有这些参数都默认为零,并且是完全可选的。

因此,当您在对象中添加或减去对象而不指定任何这些参数时,您基本上会得到相同的对象:datetime.datetime

让我们试一试:

strptime_output = datetime(2023, 7, 8, 19, 40, 6)
strptime_output + timedelta()

# Output
datetime.datetime(2023, 7, 8, 19, 40, 6)

根据我的经验,参数天、分钟、小时和周是最常用的。

你可以在这里探索它——

strptime_output = datetime(2023, 7, 8, 19, 40, 6)

# Add 2 days
strptime_output + timedelta(days=2)
## Output
datetime.datetime(2023, 7, 10, 19, 40, 6)

# Add 2 days and 4 hours
strptime_output + timedelta(days=2, hours=4)
## Output
datetime.datetime(2023, 7, 10, 23, 40, 6)

# Add 2 days, 4 hours, and 1 week
strptime_output + timedelta(days=2, hours=4, weeks=1)
## Output
datetime.datetime(2023, 7, 17, 23, 40, 6)

# Subtract 30 minutes
strptime_output - timedelta(minutes=30)
## Output
datetime.datetime(2023, 7, 8, 19, 10, 6)

同时,您一定已经注意到,对象中没有添加年份的参数。datetime

因此,要向对象添加年份,您需要使用其他可用参数。其中,您可以方便地使用天或周参数,如下所示:

strptime_output = datetime(2023, 7, 8, 19, 40, 6)

# Add 1 year using the days parameter
strptime_output + timedelta(days=365)
## Output
datetime.datetime(2024, 7, 7, 19, 40, 6)

# Add 1 year using the weeks parameter
strptime_output + timedelta(weeks=52)
## Output
datetime.datetime(2024, 7, 6, 19, 40, 6)

但是在采用这种方法增加年份时,您应该始终小心。由于您将添加固定数量的天数或周数来模拟一年,因此可以轻松忽略其他因素,例如闰年。因此,此方法将返回一个近似值。

总结: 希望你发现这篇文章非常有用,令人耳目一新,并学习了在 Python 中转换日期和时间数据的很酷的方法。

这些技术肯定会帮助您有效且高效地处理基于时间的数据。本文中探索 Python 模块时,您可以将这些技能应用于更广泛的应用程序,例如数据分析、可视化和系统自动化。

在过去的4 +年中,我一直使用Python进行数据分析和系统自动化,并发现这些技巧和方法最方便处理日期时间数据。这些技巧中的大多数,我每天都在工作中使用。

更多技巧见👇链接:

本文由 mdnice 多平台发布

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值