当前位置:

首页 > 编程开发 > 39个 Python Datetime实例,教你掌控时间

39个 Python Datetime实例,教你掌控时间

在日常生活中,我们可以用多种不同的格式来表示日期和时间,例如,7月4日、2022年3月8日、22:00或2022年12月31日23:59:59。它们使用整数和字符串的组合,或者也可以使用浮点数来表示一天、一分钟等等,各种各样的时间表示方式,确实让人眼花缭乱。不过还好,Python有datetime模块,它允许我们轻松地操作表示日期和时间的对象。在今天的文章中,我们将学习以下内容:Python中datetime模块的使用使用Python日期时间函数将字符串

39个 Python Datetime实例,教你掌控时间

在日常生活中,我们可以用多种不同的格式来表示日期和时间,例如,7 月 4 日、2022 年 3 月 8 日、22:00 或 2022 年 12 月 31 日 23:59:59。它们使用整数和字符串的组合,或者也可以使用浮点数来表示一天、一分钟等等,各种各样的时间表示方式,确实让人眼花缭乱。

不过还好,Python 有 datetime 模块,它允许我们轻松地操作表示日期和时间的对象。

39个 Python Datetime实例,教你掌控时间

在今天的文章中,我们将学习以下内容:

  •  Python 中 datetime 模块的使用
  •  使用 Python 日期时间函数将字符串转换为日期时间对象,反之亦然
  •  从日期时间对象中提取日期和时间
  •  使用时间戳
  •  对日期和时间执行算术运算
  •  使用时区
  •  创建一个倒数计时器来确定距离 2023 年新年还有多长时间

Let's do it!

如何在 Python 中使用日期时间

正如我们之前所看到的,在编程中表示日期和时间是一项非常有挑战的事情。首先,我们必须以标准的、普遍接受的格式来表示它们。幸运的是,国际标准化组织 (ISO) 制定了一个全球标准 ISO 8601,它将与日期和时间相关的对象表示为 YYYY-MM-DD HH:MM:SS,其信息范围从最重要的(年,YYYY)到 最不重要的(秒,SS)。这种格式的每一部分都表示为一个四位数或两位数。

Python 中的 datetime 模块有 5 个主要类(模块的一部分):

  •  date 操作日期对象
  •  time 操作时间对象
  •  datetime 是日期和时间的组合
  •  timedelta 允许我们使用时间区间
  •  tzinfo 允许我们使用时区

此外,我们将使用 zoneinfo 模块,它为我们提供了一种处理时区的更加现代的方式,以及 dateutil 包,它包含许多有用的函数来处理日期和时间。

让我们导入 datetime 模块并创建我们的第一个日期和时间对象:

# From the datetime module import date
from datetime import date
# Create a date object of 2000-02-03
date(2022, 2, 3)

Output:

datetime.date(2022, 2, 3)

在上面的代码中,我们从模块中导入了日期类,然后创建了 2022 年 2 月 3 日的 datetime.date 对象。需要注意的是,用于创建该对象的数字顺序与 ISO 8061 中的完全相同 (但我们省略了 0 并且只写了一个数字的月份和日期)。

关于时间的编码都是基于现实的,所以假设我们要创建一个 2000-26-03 的对象:

# Create a date object of 2000-26-03
date(2000, 26, 3)

Output:

---------------------------------------------------------------------------
ValueErrorTraceback (most recent call last)
Input In [2], in
 1 # Create a date object of 2000-26-03
----> 2 date(2000, 26, 3)
ValueError: month must be in 1..12

我们得到 ValueError: month must be in 1..12,毫无疑问,日历中没有第 26 个月,抛出异常。

让我们看看如何创建一个 datetime.time 对象:

# From the datetime module import time
from datetime import time
# Create a time object of 05:35:02
time(5, 35, 2)

Output:

datetime.time(5, 35, 2)

现在,如果我们想要在一个对象中同时包含日期和时间怎么办?我们应该使用 datetime 类:

# From the datetime module import datetime
from datetime import datetime
# Create a datetime object of 2000-02-03 05:35:02
datetime(2000, 2, 3, 5, 35, 2)

Output:

datetime.datetime(2000, 2, 3, 5, 35, 2)

不出意外,我们成功创建了 datetime 对象。我们还可以更明确地将关键字参数传递给 datetime 构造函数:

datetime(year=2000, month=2, day=3, hour=5, minute=35, second=2)

Output:

datetime.datetime(2000, 2, 3, 5, 35, 2)

如果我们只传入三个参数(年、月和日)会怎样,是否会报错呢

# Create a datetime object of 2000-02-03
datetime(2000, 2, 3)

Output:

datetime.datetime(2000, 2, 3, 0, 0)

我们可以看到,现在对象中有两个零(分别代表)小时和分钟。同时秒数也被省略了。

在许多情况下,我们想知道当前的确切时间。可以使用 datetime 类的 now() 方法:

# Time at the moment
now = datetime.now()
now

Output:

datetime.datetime(2022, 8, 1, 0, 9, 39, 611254)

我们得到一个日期时间对象,这里最后一个数字是微秒。

如果我们只需要今天的日期,我们可以使用 date 类的 today() 方法:

today = date.today()
today

Output:

datetime.date(2022, 8, 1)

如果我们只需要时间,就必须访问 datetime.now() 对象的小时、分钟和秒属性,并将它们传递给时间构造函数:

time(now.hour, now.minute, now.second)

Output:

datetime.time(11, 33, 25)

我们还可以使用 isocalendar() 函数从日期时间对象中提取周数和天数。它将返回一个包含 ISO 年份、周数和工作日数的三项元组:

# isocalendar() returns a 3-item tuple with ISO year, week number, and weekday number
now.isocalendar()

Output:

datetime.IsoCalendarDate(year=2022, week=7, weekday=1)

在 ISO 格式中,一周从星期一开始,到星期日结束。一周中的天数由从 1(星期一)到 7(星期日)的数字编码。如果我们想访问这些元组元素之一,需要使用括号表示法:

# Access week number
week_number = now.isocalendar()[1]
week_number

Output:

7

从字符串中提取日期

在数据科学和一般编程中,我们主要使用以数十种不同格式存储为字符串的日期和时间,具体取决于地区、公司或我们需要的信息粒度。有时,我们需要日期和确切时间,但在其他情况下,我们只需要年份和月份。我们该如何从字符串中提取我们需要的数据,以便将其作为日期时间(日期、时间)对象来操作呢?

fromisoformat() 和 isoformat()

我们学习的第一个将日期字符串转换为日期对象的函数是 fromisoformat,我们这样称呼它是因为它使用 ISO 8601 格式(即 YYYY-MM-DD),让我们看一个例子:

# Convert a date string into a date object
date.fromisoformat("2022-12-31")

Output:

datetime.date(2022, 12, 31)

ISO 格式也包含时间,但如果我们却不能将它传递给函数:

date.fromisoformat("2022-12-31 00:00:00")

Output:

---------------------------------------------------------------------------
ValueErrorTraceback (most recent call last)
Input In [13], in
----> 1 date.fromisoformat("2022-12-31 00:00:00")
ValueError: Invalid isoformat string: '2022-12-31 00:00:00'

当然,我们也可以进行逆向运算,将 datetime 对象转换为 ISO 格式的日期字符串,我们应该使用 isoformat():

# Convert a datetime object into a string in the ISO format
date(2022, 12, 31).isoformat()

Output:

'2022-12-31'

strptime()

为了解决上述 ValueError 问题,我们可以使用 strptime() 函数,该函数可以将任意日期/时间字符串转换为日期时间对象。我们的字符串不一定需要遵循 ISO 格式,但我们应该指定字符串的哪一部分代表哪个日期或时间单位(年、小时等)。让我们看一个例子,首先,我们将使用严格的 ISO 格式将字符串转换为日期时间对象:

# Date as a string
iso_date = "2022-12-31 23:59:58"
# ISO format
iso_format = "%Y-%m-%d %H:%M:%S"
# Convert the string into a datetime object
datetime.strptime(iso_date, iso_format)

Output:

datetime.datetime(2022, 12, 31, 23, 59, 58)

在第一行,我们创建一个日期/时间字符串。在第二行中,我们使用特殊代码指定字符串的格式,该代码包含一个百分号,后跟一个编码日期或时间单位的字符。最后,在第三行中,我们使用 strptime() 函数将字符串转换为日期时间对象。这个函数有两个参数:字符串和字符串的格式。

我们上面使用的代码还可以编码其他日期和时间单位,如工作日、月份名称、周数等。

代码

示例

说明

%A

Monday

完整的工作日名称

%B

December

全月名称

%W

2

周数(星期一为一周的第一天)

让我们再看几个使用其他格式的示例:

# European date as a string
european_date = "31-12-2022"
# European format
european_format = "%d-%m-%Y"
# Convert the string into a datetime object
datetime.strptime(european_date, european_format)

Output:

datetime.datetime(2022, 12, 31, 0, 0)

如上所示,字符串已成功转换,但还有额外的零表示时间字段,让我们看一个使用其他代码的示例:

# Full month name date
full_month_date = "12 September 2022"
# Full month format
full_month_format = "%d %B %Y"
# Convert the string into a datetime object
datetime.strptime(full_month_date, full_month_format)

Output:

datetime.datetime(2022, 9, 12, 0, 0)

还是可以正常转换,但是需要注意的是,我们定义的格式应该与日期字符串的格式相匹配。因此,如果我们有空格、冒号、连字符或其他字符来分隔时间单位,那么它们也应该在代码字符串中。否则,Python 将抛出 ValueError:

# Full month name date
full_month_date = "12 September 2022"
# Wrong format (missing space)
full_month_format = "%d%B %Y"
# Convert the string into a datetime object
datetime.strptime(full_month_date, full_month_format)

Output:

---------------------------------------------------------------------------
ValueErrorTraceback (most recent call last)
Input In [18], in
 5 full_month_format = "%d%B %Y"
 7 # Convert the string into a datetime object
----> 8 datetime.strptime(full_month_date, full_month_format)
File ~/coding/dataquest/articles/using-the-datetime-package/env/lib/python3.10/_strptime.py:568, in _strptime_datetime(cls, data_string, format)
 565 def _strptime_datetime(cls, data_string, format="%a %b %d %H:%M:%S %Y"):
 566 """Return a class cls instance based on the input string and the
 567 format string."""
--> 568 tt, fraction, gmtoff_fraction = _strptime(data_string, format)
 569 tzname, gmtoff = tt[-2:]
 570 args = tt[:6] + (fraction,)
File ~/coding/dataquest/articles/using-the-datetime-package/env/lib/python3.10/_strptime.py:349, in _strptime(data_string, format)
 347 found = format_regex.match(data_string)
 348 if not found:
--> 349 raise ValueError("time data %r does not match format %r" %
 350(data_string, format))
 351 if len(data_string) != found.end():
 352 raise ValueError("unconverted data remains: %s" %
 353 data_string[found.end():])
ValueError: time data '12 September 2022' does not match format '%d%B %Y'

可以看到,即使缺少一个空格也可能导致错误!

将日期时间对象转换为字符串

strftime()

在 Python 中,我们还可以使用 strftime() 函数将日期时间对象转换为字符串。它有两个参数:一个日期时间对象和输出字符串的格式。

# Create a datetime object
datetime_obj = datetime(2022, 12, 31)
# American date format
american_format = "%m-%d-%Y"
# European format
european_format = "%d-%m-%Y"
# American date string
print(f"American date string: {datetime.strftime(datetime_obj, american_format)}.")
# European date string
print(f"European date string: {datetime.strftime(datetime_obj, european_format)}.")

Output:

American date string: 12-31-2022.
European date string: 31-12-2022.

我们采用相同的日期时间对象并将其转换为两种不同的格式。我们还可以指定其他格式,例如完整的月份名称后跟日期和年份。

full_month = "%B %d, %Y"
datetime.strftime(datetime_obj, full_month)

Output:

'December 31, 2022'

另一种使用 strftime 的方法是将它放在 datetime 对象之后:

datetime_obj = datetime(2022, 12, 31, 23, 59, 59)
full_datetime = "%B %d, %Y %H:%M:%S"
datetime_obj.strftime(full_datetime)

Output:

'December 31, 2022 23:59:59'

在实际使用当中,如果我们想提取不同年份 12 月 31 日的工作日名称,strftime() 可能很方便:

# Extract the weekday name of December 31
weekday_format = "%A"
for year in range(2022, 2026):
 print(f"Weekday of December 31, {year} is {date(year, 12, 31).strftime(weekday_format)}.")

Output:

Weekday of December 31, 2022 is Saturday.
Weekday of December 31, 2023 is Sunday.
Weekday of December 31, 2024 is Tuesday.
Weekday of December 31, 2025 is Wednesday.

时间戳

在编程中,通常会看到以 Unix 时间戳格式存储的日期和时间,这种格式将任何日期表示为数字。一般情况时间戳是从 1970 年 1 月 1 日 00:00:00 UTC(协调世界时)开始的 Unix 纪元经过的秒数。我们可以使用 timestamp() 函数计算这个数字:

new_year_2023 = datetime(2022, 12, 31)
datetime.timestamp(new_year_2023)

Output:

1672441200.0

1672441200 就是从 Unix 纪元开始到 2022 年 12 月 31 日之间的秒数。

我们可以使用 fromtimestamp() 函数执行逆运算:

datetime.fromtimestamp(1672441200)

Output:

datetime.datetime(2022, 12, 31, 0, 0)

带日期的算术运算

有时我们可能想要计算两个日期之间的差异或对日期和时间执行其他算术运算。幸运的是,Python 的工具包中有许多工具可以执行此类计算。

基本算术运算

我们可以执行的第一个操作是计算两个日期之间的差异。为此,我们使用减号:

# Instatiate two dates
first_date = date(2022, 1, 1)
second_date = date(2022, 12, 31)
# Difference between two dates
date_diff = second_date - first_date
# Function to convert datetime to string
def dt_string(date, date_format="%B %d, %Y"):
 return date.strftime(date_format)
print(f"The number of days and hours between {dt_string(first_date)} and {dt_string(second_date)} is {date_diff}.")

Output:

The number of days and hours between January 01, 2022 and December 31, 2022 is 364 days, 0:00:00

让我们看看 first_date - second_date 返回什么类型的对象:

type(date_diff)

Output:

datetime.timedelta

此对象的类型是 datetime.timedelta,它的名称中有 delta,指的是一个绿色字母 delta,在科学和工程中,描述了一种变化<实际上,这里它代表了时间上的变化(差异)。

如果我们只对两个日期之间的天数感兴趣怎么办?我们可以访问 timedelta 对象的不同属性,其中之一称为 .days。

print(f"The number of days between {dt_string(first_date)} and {dt_string(second_date)} is {(date_diff).days}.")

Output:

The number of days between January 01, 2022 and December 31, 2022 is 364.

timedelta() 时间增量

现在我们知道了 timedelta 对象,是时候介绍 timedelta() 函数了。它允许我们通过加减时间单位(如天、年、周、秒等)对时间对象执行许多算术运算。例如,我们可能想知道从现在起 30 天后是一周中的哪一天。为此,我们必须创建一个表示当前时间的对象和一个定义我们添加到其中的时间量的 timedelta 对象:

# Import timedelta
from datetime import timedelta
# Current time
now = datetime.now()
# timedelta of 30 days
one_month = timedelta(days=30)
# Day in one month/using dt_string function defined above
print(f"The day in 30 days is {dt_string(now + one_month)}.")

Output:

The day in 30 days is March 16, 2022.

如果我们查看 timedelta 函数的帮助页面 (help(timedelta)),我们会看到它有以下参数:days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours= 0,周=0。因此我们还可以练习在日期中添加或减去其他时间单位。例如,我们可以计算 2030 年新年前 12 小时的时间:

# New year 2030
new_year_2030 = datetime(2030, 1, 1, 0, 0)
# timedelta of 12 hours
twelve_hours = timedelta(hours=12)
# Time string of 12 hours before New Year 2023
twelve_hours_before = (new_year_2030 - twelve_hours).strftime("%B %d, %Y, %H:%M:%S")
# Print the time 12 hours before New Year 2023
print(f"The time twelve hours before New Year 2030 will be {twelve_hours_before}.")

Output:

The time twelve hours before New Year 2030 will be December 31, 2029, 12:00:00.

我们还可以组合 timedelta() 函数的多个参数来计算出更具体的时间。例如,从现在起 27 天 3 小时 45 分钟后的时间是多少?

# Current time
now = datetime.now()
# Timedelta of 27 days, 3 hours, and 45 minutes
specific_timedelta = timedelta(days=27, hours=3, minutes=45)
# Time in 27 days, 3 hours, and 45 minutes
twenty_seven_days = (now + specific_timedelta).strftime("%B %d, %Y, %H:%M:%S")
print(f"The time in 27 days, 3 hours, and 45 minutes will be {twenty_seven_days}.")

Output:

The time in 27 days, 3 hours, and 45 minutes will be March 13, 2022, 15:18:39.

relativedelta() 相对增量

我们可以从帮助页面中看到该功能不允许我们使用几个月或几年。为了克服这个限制,我们可以使用 dateutil 包中的 relativedelta 函数。此函数与 timedelta() 非常相似,但它扩展了更多的功能。

例如,我们想从当前时间中减去 2 年 3 个月 4 天 5 小时:

# Import relativedelta
from dateutil.relativedelta import relativedelta
# Current time
now = datetime.now()
# relativedelta object
relative_delta = relativedelta(years=2, months=3, days=4, hours=5)
two_years = (now - relative_delta).strftime("%B %d, %Y, %H:%M:%S")
print(f"The time 2 years, 3 months, 4 days, and 5 hours ago was {two_years}.")

Output:

The time 2 years, 3 months, 4 days, and 5 hours ago was November 10, 2019, 06:33:40.

我们还可以使用 relativedelta() 来计算两个日期时间对象之间的差异:

relativedelta(datetime(2030, 12, 31), now)

Output:

relativedelta(years=+8, months=+10, days=+16, hours=+12, minutes=+26, seconds=+19, microseconds=+728345)

这些算术运算可能看起来非常抽象和不切实际,但实际上,它们在许多应用程序中都很有用。

比如说,我们脚本中的某个操作应该只在特定日期前 30 天执行。我们可以定义一个保存当前时间的变量,并为其添加一个 30 天的 timedelta 对象,如果今天是这一天,就会触发相关操作!

还有,假设我们正在使用 pandas 处理数据集,其中一列包含一些日期。想象一下,我们有一个数据集,其中保存着我们公司一年中的每一天的利润。我们想要创建另一个数据集,该数据集将保存距当前日期正好一年的日期,并预测每一天的利润,此时我们一定会在日期上使用算术计算!

使用时区

下面我们来看一看时区,它们可以有不同的形式。我们还应该知道,一些地区实施夏令时 (DST),而另一些地区则没有。

Python 区分两种类型的日期和时间对象:naive 和 aware。一个 naive 对象不保存任何有关时区的信息,而 aware 对象则保存了它。

首先,让我们看一个 naive 时间对象:

# Import tzinfo
from datetime import tzinfo
# Naive datetime
naive_datetime = datetime.now()
# Naive datetime doesn't hold any timezone information
type(naive_datetime.tzinfo)

Output:

NoneType

从 Python 3.9 开始,使用 Internet Assigned Numbers Authority 数据库实现了时区的具体实现,实现此功能的模块称为 zoneinfo。

让我们使用 zoneinfo,特别是 ZoneInfo 类创建一个感知日期时间对象,它是 datetime.tzinfo 抽象类的一个实现:

# Import ZoneInfo
from zoneinfo import ZoneInfo
utc_tz = ZoneInfo("UTC")
# Aware datetime object with UTC timezone
dt_utc = datetime.now(tz=utc_tz)
# The type of an aware object implemented with ZoneInfo is zoneinfo.ZoneInfo
type(dt_utc.tzinfo)

Output:

zoneinfo.ZoneInfo

对于拥有 aware 的 datetime 对象具有有关时区的信息(实现为 zoneinfo.ZoneInfo 对象)。

让我们看几个例子,我们想确定中欧和加利福尼亚的当前时间。

首先,我们可以在 `zoneinfo 中列出所有可用的时区:

import zoneinfo
# Will return a long list of timezones (opens many files!)
zoneinfo.available_timezones()

Output:

{'Africa/Abidjan',
'Africa/Accra',
'Africa/Addis_Ababa',
'Africa/Algiers',
'Africa/Asmara',
'Africa/Asmera',
'Africa/Bamako',
'Africa/Bangui',
'Africa/Banjul',
'Africa/Bissau',
'Africa/Blantyre',
'Africa/Brazzaville',
'Africa/Bujumbura',
'Africa/Cairo',
'Africa/Casablanca',
'Africa/Ceuta',
'Africa/Conakry',
'Africa/Dakar',
'Africa/Dar_es_Salaam',
'Africa/Djibouti',
'Africa/Douala',
...
'build/etc/localtime'}

现在我们可以使用 ZoneInfo 来确定不同区域的当前时间:

# Function to convert datetime into ISO formatted time
def iso(time, time_format="%Y-%m-%d %H:%M:%S"):
 return time.strftime(time_format)
# CET time zone
cet_tz = ZoneInfo("Europe/Paris")
# PST time zone
pst_tz = ZoneInfo("America/Los_Angeles")
# Current time in Central Europe
dt_cet = datetime.now(tz=cet_tz)
# Current time in California
dt_pst = datetime.now(tz=pst_tz)
print(f"Current time in Central Europe is {iso(dt_cet)}.")
print(f"Current time in California is {iso(dt_pst)}.")

Output:

Current time in Central Europe is 2022-02-14 11:33:42.
Current time in California is 2022-02-14 02:33:42.

让我们打印 datetime.now(tz=cet_tz):

print(datetime.now(tz=cet_tz))

Output:

2022-02-14 11:33:43.048967+01:00

我们看到有 +01:00,它表示 UTC 偏移量。事实上,CET 时区比 UTC 早一小时。

此外,ZoneInfo 类处理夏令时。例如,我们可以将一天(24 小时)添加到 DST 更改发生的一天。

# Define timedelta
time_delta = timedelta(days=1)
# November 5, 2022, 3 PM
november_5_2022 = datetime(2022, 11, 5, 15, tzinfo=pst_tz) # Note that we should use tzinfo in the datetime construct
print(november_5_2022)
# Add 1 day to November 5, 2022
print(november_5_2022 + time_delta)

Output:

2022-11-05 15:00:00-07:00
2022-11-06 15:00:00-08:00

正如我们所见,偏移量从 -07:00 变为 -08:00,但时间保持不变(15:00)。

2023 年新年倒数计时器

New Your City 的时代广场在新年前夜吸引了成千上万的人。让我们应用到目前为止所学的一切来为时代广场除夕创建一个倒数计时器!

在这里,我们将使用 dateutil 包中的 tz,它允许我们设置本地时区来演示 dateutil 包的实用程序。但是我们也可以使用 zoneinfo 中的 build/etc/localtime 时区来做同样的事情。

from zoneinfo import ZoneInfo
from dateutil import tz
from datetime import datetime
def main():
 """Main function."""
 # Set current time in our local time zone
 now = datetime.now(tz=tz.tzlocal())
 # New York City time zone
 nyc_tz = ZoneInfo("America/New_York")
 # New Year 2023 in NYC
 new_year_2023 = datetime(2023, 1, 1, 0, 0, tzinfo=nyc_tz)
 # Compute the time left to New Year in NYC
 countdown = relativedelta(new_year_2023, now)
 # Print time left to New Year 2023
 print(f"New Year in New Your City will come on: {new_year_2023.strftime('%B %-d, %Y %H:%M:%S')}.")
 print(f"Time left to New Year 2023 in NYC is: {countdown.months} months, {countdown.days} days, {countdown.hours} hours, {countdown.minutes} minutes, {countdown.seconds} seconds.")
if __name__ == "__main__":
 main()

Output:

New Year in New Your City will come on: January 1, 2023 00:00:00.

Time left to New Year 2023 in NYC is: 10 months, 17 days, 18 hours, 26 minutes, 16 seconds.

我们将代码包装在 main() 函数中,现在我们可以在 .py 文件中使用它。在这个脚本中,我们处理了时区,创建了一个 datetime 对象,使用 strftime() 将其转换为字符串,甚至访问了 relativedelta 对象的时间属性!

好了,这就是今天分享的全部内容,喜欢就点个赞吧~

本文内容来源于互联网,如有侵权请联系删除。
作者最新文章
编程开发 时间 Python
相关文章 更多
C++动态数组初始化怎么写?常用语句与代码示例
C++动态数组初始化怎么写?常用语句与代码示例

深入解析C++中动态数组的初始化机制,涵盖new操作符的不同用法、基本类型与类对象的初始化差异,以及为何在现代C++开发中应优先使用std::vector。

Python安装后怎么打开:使用IDLE或命令行启动解释器
Python安装后怎么打开:使用IDLE或命令行启动解释器

刚在Windows安装好Python却不知道如何启动?本文详细演示如何通过开始菜单找到并打开IDLE集成开发环境,以及如何在PowerShell或命令提示符中使用python和py命令启动交互式解释器、运行.py脚本文件。包含退出解释器的方法及常见启动问题排查,帮助初学者快速验证安装成功并开始编写代码。

Windows系统Python安装教程:下载、勾选PATH及环境变量配置
Windows系统Python安装教程:下载、勾选PATH及环境变量配置

针对Windows初学者的Python安装实战指南。详细讲解如何从Python官网下载匹配架构的安装包,重点演示安装首屏勾选“Add python.exe to PATH”的关键操作,并提供使用python --version和py命令验证环境变量的具体步骤,帮助新手快速搭建开发环境并排查路径问题。

麒麟OS如何查看Python进程的运行状态
麒麟OS如何查看Python进程的运行状态

要想确认麒麟OS中Python程序的运行状态以及资源占用情况,我们可以这样做:用ps -ef | grep python来筛选进程;通过top命令,按P键排序查看实时负载;使用pgrep -f "script.py"精准获取PID;借助lsof -p PID验证文件打开状态。另外,还可以结合syst

Python在Debian上如何配置SSL证书
Python在Debian上如何配置SSL证书

在Debian系统上配置SSL证书通常涉及以下几个步骤:安装Web服务器:首先,你需要一个Web服务器,比如Apache或Nginx。这里以Apache为例。sudo apt updatesudo apt install apache2获取SSL证书:你可以从Let’s Encrypt免费获取SSL

统信UOS怎么安装Python开发环境
统信UOS怎么安装Python开发环境

要想让Python项目在统信UOS上正常运行,得先安装python3、python3-pip、python3-venv、python3-dev以及build-essential等组件。具体操作就是执行sudo apt install命令来一步到位完成安装,同时别忘了配置清华镜像源来给pip加速哦。在

纯Python方案实现中英文全文搜索
纯Python方案实现中英文全文搜索

在互联网上的各类网站中,无论大小,基本上都会有一个搜索框,用来给用户对内容进行搜索,小到站点搜索,大到搜索引擎搜索。从简单的来说,搜索功能确实很简单,一个简单的select语句就可以实现数据的搜索。而从复杂的来看,无论是搜索的精度还是搜索的效率,都是有很深的研究范围的。对于简单的搜索功能来说,一个s

Mac如何取消通过Python脚本运行的关机程序
Mac如何取消通过Python脚本运行的关机程序

立即在终端输入sudo shutdown -c取消倒计时关机,成功后显示“Shutdown cancelled”;若存在pmset重复任务,需再执行sudo pmset repeat cancel清除。Mac因Python脚本执行了os.system("sudo shutdown -h +10")或

Pythonasyncio异步并发与多固定出口IP调度实战
Pythonasyncio异步并发与多固定出口IP调度实战

之前写过一篇同步场景下用 Python 管理多个固定出口 IP 的实践(ExitPool + requests/httpx),覆盖了健康检查、故障转移和连接池复用。但在实际业务中,越来越多的场景用 asyncio 做高并发采集或批量接口调用——异步事件循环下多出口的管理方式和同步场景完全不同:单线程

Python在静态出口IP产品中的实战:从地址漂移巡检到多IP故障切换
Python在静态出口IP产品中的实战:从地址漂移巡检到多IP故障切换

写在前面:为什么静态出口 IP 不是"买了就行"不少团队在引入静态出口 IP 产品时,第一反应往往是:“地址配上去,这事就算完了。”可真到了真实业务里,静态出口 IP 真正能体现价值的地方,往往不在分配这一步,而在分配之后怎么管:地址有没有漂移,质量是否达标,某一条线路突然不可用时怎么切换,连接层又

查看更多
精品专题 更多
装机必备
装机必备

正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

Windows
Windows

正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

macOS软件
macOS软件

正软商城macOS软件专区,精选适用于Mac电脑的办公、设计、影音、效率、开发和系统工具,提供软件功能介绍、macOS兼容版本、正版授权及购买下载服务。

Mac软件 更多
灵活计算器
灵活计算器
macOS/iOS/Android

灵活计算器是一款笔记式算数应用,支持实时计算、动态关联和云端同步功能。记录、整理和输出之间的过渡会更自然,适合长期写作、做笔记或持续沉淀个人内容。

赤友清理大师
赤友清理大师
macOS

赤友清理大师是一款为 Mac 设计的智能清理优化工具,可精准扫描垃圾、大文件、重复文件等,释放磁盘空间。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。

极度公式
极度公式
Windows/macOS/Linux

极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。

WINDOWS 更多
Windows 10
Windows 10
Windows

Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。

极度公式
极度公式
Windows/macOS/Linux

极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。

密码键盘
密码键盘
Windows/macOS/iOS/Android

密码键盘是一款兼具安全性与便捷性的高效密码管理器。日常使用里的持续防护和信息管理会更突出,适合把安全控制放进长期使用流程中的场景。