I have a dict with dates, some are timestamps, some date as string. I would like to iterate over a dict. If the val is as sting, convert it to a timestamp. If not only print it.
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)
CodePudding user response:
Something like this?
Using datetime
to parse and format the string
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)
Which outputs:
2017-01-01 12:00:00
01.01.2017
Or, as you're already using pandas you can create a pd.Timestamp
from the parsed datetime
object:
for key, val in timedict.items():
if isinstance(val, str):
val = pd.Timestamp(datetime.strptime(val, "%Y-%m-%d"))
print(val)
else:
print(val)