首页 > 解决方案 > 如何以 python 日期时间格式指定历史日期

问题描述

我有一个代码,该代码仅针对当前日期和时间执行。现在我需要为一个历史日期执行它,所以我需要替换下面提到的日期变量:

curr_month = dt.datetime.now()

today_day = dt.datetime.today()

输出

datetime.datetime(2020, 10, 2, 22, 36, 9, 155118)

我可以使用什么格式来指定历史日期,以便它采用上述确切格式的 DateTime 数据类型?

标签: pythonpandasdatetime

解决方案


在 pandas 中,可以根据您的需要使用datetime.datetime或对象。pd.Timestamp

import pandas as pd
import datetime as dt

# datetime objects
historic_date = dt.datetime(2020,1,1)  

date_str = '2020-01-01'
historic_date2 = dt.datetime.strptime(date_str, '%Y-%m-%d')  

# Timestamp objects
historic_date3 = pd.to_datetime(date_str)  
historic_date4 = pd.Timestamp(date_str) 
historic_date5 = pd.Timestamp(historic_date) 


推荐阅读