python如何读取日期

原创
ithorizon 7个月前 (09-30) 阅读数 56 #Python

Python中处理日期的几种方法

Python提供了多种方式来处理和读取日期,以下是其中的几种方法:

1. 使用time模块

Python的time模块内置了多种处理日期的函数,可以使用time.time()获取当前时间,使用time.strftime()格式化日期。

示例:

import time
获取当前时间
current_time = time.time()
格式化日期
formatted_time = time.strftime("%Y-%m-%d", current_time)
print(formatted_time)

2. 使用datetime模块

datetime模块提供了更完整的日期和时间处理功能,可以使用datetime.datetime.now()获取当前日期和时间,使用datetime.datetime.strftime()格式化日期。

示例:

import datetime
获取当前日期和时间
current_datetime = datetime.datetime.now()
格式化日期
formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_datetime)

3. 使用pandas库

pandas库是一个强大的数据处理库,也可以用来处理和读取日期,可以使用pandas.to_datetime()将字符串或其他类型转换为日期,使用DataFrame的loc或iloc进行筛选。

示例:

import pandas as pd
将字符串转换为日期
date_string = "2023-07-06"
date_object = pd.to_datetime(date_string)
print(date_object)


热门