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

Python日期和时间函数:如何使用datetime和time模块以及示例

发布时间:2023-05-31 19:24:50

Python中datetime和time模块提供了方便的日期和时间函数,可以用来创建、操作和比较日期和时间对象。下面将对这两个模块的常用函数进行介绍,并通过实例来详细说明使用方法。

一、datetime模块

1. datetime.datetime.now(): 返回当前时间,类型为datetime.datetime对象。

示例:

import datetime

now = datetime.datetime.now()
print(now)

输出:

2022-03-18 16:31:48.742941

2. datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0): 返回指定日期和时间,类型为datetime.datetime对象。

示例:

import datetime

dt = datetime.datetime(2022, 3, 18, 16, 40, 30)
print(dt)

输出:

2022-03-18 16:40:30

3. datetime.datetime.strptime(date_string, format): 将指定格式的字符串转换为datetime.datetime对象。

示例:

import datetime

str_time = '2022-03-18 16:40:30'
datetime_time = datetime.datetime.strptime(str_time, '%Y-%m-%d %H:%M:%S')
print(datetime_time)

输出:

2022-03-18 16:40:30

4. datetime.datetime.strftime(format): 将datetime.datetime对象转换为指定格式的字符串。

示例:

import datetime

now = datetime.datetime.now()
str_time = now.strftime('%Y-%m-%d %H:%M:%S')
print(str_time)

输出:

2022-03-18 16:31:48

5. datetime.datetime.timestamp(): 返回指定datetime.datetime对象对应的时间戳。

示例:

import datetime

now = datetime.datetime.now()
timestamp = now.timestamp()
print(timestamp)

输出:

1647639308.58

二、time模块

1. time.time(): 返回当前时间距离1970年1月1日0时0分0秒的秒数,类型为float。

示例:

import time

current_time = time.time()
print(current_time)

输出:

1647639308.9119475

2. time.localtime([secs]): 将指定的秒数转换为本地时间,返回一个时间元组tm_year(年)、tm_mon(月)、tm_mday(日)、tm_hour(小时)、tm_min(分钟)、tm_sec(秒数)、tm_wday(星期几)、tm_yday(一年中的第几天)、tm_isdst(是否为夏令时)。

示例:

import time

local_time = time.localtime()
print(local_time)

输出:

time.struct_time(tm_year=2022, tm_mon=3, tm_mday=18, tm_hour=16, tm_min=46, tm_sec=48, tm_wday=4, tm_yday=77, tm_isdst=0)

3. time.sleep(secs): 使当前线程暂停指定的秒数。

示例:

import time

print('start')
time.sleep(5)
print('end')

输出:

start
end

在输出end之前会暂停5秒钟。

4. time.strftime(format[, t]): 将指定的时间元组或时间戳转换为格式化的字符串。

示例:

import time

local_time = time.localtime()
str_time = time.strftime('%Y-%m-%d %H:%M:%S', local_time)
print(str_time)

输出:

2022-03-18 16:50:51

5. time.strptime(date_string[, format]): 将指定格式的字符串转换为时间元组。

示例:

import time

str_time = '2022-03-18 16:50:51'
time_tuple = time.strptime(str_time, '%Y-%m-%d %H:%M:%S')
print(time_tuple)

输出:

time.struct_time(tm_year=2022, tm_mon=3, tm_mday=18, tm_hour=16, tm_min=50, tm_sec=51, tm_wday=4, tm_yday=77, tm_isdst=-1)

以上就是datetime和time模块的常用函数介绍和示例,可以通过这些函数方便地处理时间和日期。