假設我得到了一個部分日期時間字串。我希望獲得它代表的日期時間,以及給定日期時間的解析度是多少。
例如:
"2021-01-06 12"->2021-01-06 12:00:00.000000和"hour""2020-03"->2020-03-01 00:00:00.000000和"month""2020-03-01"->2020-03-01 00:00:00.000000和"day"
這個想法是使用給定的部分日期時間字串作為時間范圍規范。意思是不要寫"All of March, 2020",只要寫"2020-03"。
這個問題可以簡化為pandas框架的答案,盡管給定了上面例子中的部分字串,pd.Timestamp(...)決議它很好(例如pd.Timestamp("2020-03") == pd.Timestamp('2020-03-01 00:00:00.000000'))。
提前致謝!
編輯:似乎內部函式pandas._libs.tslibs.parsing.parse_datetime_string_with_reso回傳了我想要的。有誰知道我如何訪問它(無法使用 訪問from pandas._libs.tslibs.parsing import parse_datetime_string_with_reso)?
uj5u.com熱心網友回復:
具體解決問題的這一部分:
編輯:似乎內部函式 pandas._libs.tslibs.parsing.parse_datetime_string_with_reso 回傳我想要的。有誰知道我如何訪問它(使用 from pandas._libs.tslibs.parsing import parse_datetime_string_with_reso 無法訪問)?
您可以使用from pandas._libs.tslibs.parsing import parse_time_stringwhich 內部呼叫parse_datetime_string_with_reso并回傳解析度。
uj5u.com熱心網友回復:
dateutil 有一個很好的決議器,允許輸入字串缺少部分:
from dateutil import parser
dates = ["2021-01-06 12", "2020-03", "2020-03-01"]
for date in dates:
if len(date.split('-')) <= 2:
# If day is missing, resulting day will be the same as
# the current day of month instead of '01'.
date = '-01'
parsed = parser.parse(date)
print(parsed)
輸出:
2021-01-06 12:00:00
2020-03-01 00:00:00
2020-03-01 00:00:00
uj5u.com熱心網友回復:
你可以試試這個https://pypi.org/project/datefinder/ 一個用于在字串中定位日期的 python 模塊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/337068.html
標籤:Python 熊猫 约会时间 日期时间格式 蟒蛇日期时间
下一篇:兩列之間的營業時間
