欢迎访问宙启技术站
智能推送

Python时间日期处理:10个常用函数

发布时间:2023-06-26 01:53:16

Python是一种高效的编程语言,可以处理各种类型的数据,包括日期和时间。Python提供了许多内置函数来处理日期和时间。在此,我们将介绍10个常用的Python日期和时间处理函数。

1. datetime.now()函数

datetime.now()函数返回当前日期和时间。以下是示例代码。

from datetime import datetime

now = datetime.now()

print("当前日期和时间是:", now)

这将输出当前日期和时间,格式为“年月日 时分秒”。

2. datetime.date()函数

datetime.date()函数返回指定日期的日期部分,即年、月和日。以下是示例代码。

from datetime import datetime

now = datetime.now()
date = datetime.date(now)

print("只有日期部分是:", date)

这将输出指定日期的日期部分(年、月和日)。

3. datetime.time()函数

datetime.time()函数返回指定日期的时间部分,即时、分和秒。以下是示例代码。

from datetime import datetime

now = datetime.now()
time = datetime.time(now)

print("只有时间部分是:", time)

这将输出指定日期的时间部分(小时、分钟和秒)。

4. datetime.strftime()函数

datetime.strftime()函数将日期对象格式化为一个字符串。以下是示例代码。

from datetime import datetime

now = datetime.now()
date_string = now.strftime("%Y-%m-%d %H:%M:%S")

print("格式化后的日期时间是:", date_string)

这将输出格式化后的日期和时间,格式为“YYYY-MM-DD HH:MM:SS”。

5. datetime.strptime()函数

datetime.strptime()函数解析一个字符串并返回一个datetime对象。以下是示例代码。

from datetime import datetime

date_string = "2022-09-30 16:30:00"
date_object = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")

print("解析后的日期时间是:", date_object)

这将输出解析后的日期和时间,格式为“年月日 时分秒”。

6. datetime.timedelta()函数

datetime.timedelta()函数表示两个日期之间的差值。以下是示例代码。

from datetime import datetime, timedelta

date1 = datetime(2022, 9, 30, 16, 30, 0)
date2 = datetime(2022, 10, 1, 16, 30, 0)
delta = date2 - date1

print("两个日期之间的差值是:", delta)

这将输出两个日期之间的差值,格式为“天数:秒数”。

7. datetime.replace()函数

datetime.replace()函数用指定的参数替换当前日期对象的某些部分。以下是示例代码。

from datetime import datetime

date = datetime(2022, 9, 30, 16, 30, 0)
new_date = date.replace(hour=17, minute=30)

print("新的日期时间是:", new_date)

这将输出被替换后的日期和时间,格式为“年月日 小时:分钟:秒”。

8. date.weekday()函数

date.weekday()函数返回指定日期的星期几,其中0表示星期一,6表示星期日。以下是示例代码。

from datetime import date

d = date(2022, 9, 30)
weekday_number = d.weekday()

print("星期几是:", weekday_number)

这将输出指定日期是星期几。

9. time.sleep()函数

time.sleep()函数让程序暂停指定的时间。以下是示例代码。

import time

print("开始...")
time.sleep(5)
print("结束!")

这将输出“开始...”后暂停5秒,然后输出“结束!”。

10. calendar.month()函数

calendar.month()函数返回指定年月的月历。以下是示例代码。

import calendar

year = 2022
month = 9

print(calendar.month(year, month))

这将输出指定年月的月历。