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

Python中的时间日期函数及其使用方法?

发布时间:2023-08-21 14:11:10

在Python中,有许多内置的模块和函数可以用来处理日期和时间。下面是一些常用的时间日期函数及其使用方法:

1. time模块:

- time.time():返回当前时间的时间戳,即自1970年1月1日午夜以来的秒数。

- time.sleep(seconds):暂停指定的秒数。

- time.localtime():返回当前的时间和日期。

- time.strftime(format[, t]):将时间转换为指定格式的字符串。

- time.strptime(string[, format]):将字符串转换为时间。

2. datetime模块:

- datetime.datetime.now():返回当前的日期和时间。

- datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]):创建一个指定的日期和时间。

- datetime.datetime.strptime(date_string, format):将字符串转换为日期和时间。

- datetime.datetime.strftime(format):将日期和时间格式化为字符串。

3. calendar模块:

- calendar.month(year, month[, w[, l]]):返回指定年份和月份的日历字符串。

- calendar.weekday(year, month, day):返回指定日期的星期几。

4. timedelta类:

- timedelta(days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]):表示两个日期或时间之间的差距。

- timedelta.total_seconds():返回时间差距的总秒数。

下面是一个使用日期和时间函数的示例:

import time
import datetime
import calendar

# 使用time模块
print(time.time())
time.sleep(2)
print(time.localtime())
print(time.strftime("%Y-%m-%d %H:%M:%S"))

# 使用datetime模块
print(datetime.datetime.now())
print(datetime.datetime(2022, 1, 1))
print(datetime.datetime.strptime("2022-01-01", "%Y-%m-%d"))
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

# 使用calendar模块
print(calendar.month(2022, 1))
print(calendar.weekday(2022, 1, 1))

# 使用timedelta类
delta = datetime.timedelta(days=1)
print(datetime.datetime.now() - delta)
print(delta.total_seconds())

以上只是时间日期处理的一小部分函数和方法,Python还提供了许多其他功能强大的模块和函数,供开发者根据需求选择使用。