我有一个日期字典,一些是时间戳,一些日期作为字符串。我想遍历一个字典。如果val为sting,则将其转换为时间戳。如果不是,就打印出来。
import pandas as pd
ts = pd.Timestamp('2017-01-01T12')
date = '2017-01-01'
timedict = {
"timestamp": ts,
"date": date
}
for key, val in timedict.items():
if val == #string:
val.strftime('%d.%m.%Y')
print(val)
else:
print(val)
像这样?
使用datetime
解析和格式化字符串
from datetime import datetime
import pandas as pd
ts = pd.Timestamp("2017-01-01T12")
date = "2017-01-01"
timedict = {
"timestamp": ts,
"date": date,
}
for key, val in timedict.items():
if isinstance(val, str):
val = datetime.strptime(val, "%Y-%m-%d")
val = val.strftime("%d.%m.%Y")
print(val)
else:
print(val)
输出:
2017-01-01 12:00:00
01.01.2017
或者,由于您已经在使用pandas,您可以从解析的datetime
对象创建pd.Timestamp
:
for key, val in timedict.items():
if isinstance(val, str):
val = pd.Timestamp(datetime.strptime(val, "%Y-%m-%d"))
print(val)
else:
print(val)