Reputation: 41
I have the following code and I need the original time stamp as string (2021-02-09T12:03:40Z) in the dictionary. Please can you advise me how to do that?
import pandas as pd
def main():
df1 = pd.DataFrame({'id': ['D0'],
'date': pd.to_datetime(pd.Series(['2021-02-09T12:03:40Z']))}
)
print(df1)
dictionary = df1.to_dict('records')
print(dictionary)
if __name__ == "__main__":
main()
Current output gives me this format, which I can not use in API method:
[{'id': 'D0', 'date': Timestamp('2021-02-09 12:03:40+0000', tz='UTC')}]
What I need is the original format 2021-02-09T12:03:40Z.
Solution:
def main():
print(sys.version)
df1 = pd.DataFrame({'id': ['D0'],
'date': pd.to_datetime(pd.Series(['2021-02-09T12:03:40Z']))}
)
print(df1)
df1['date'] = df1.date.dt.strftime("%Y-%m-%dT%TZ")
dictionary = df1.to_dict('records')
print(dictionary)
if __name__ == "__main__":
main()
Upvotes: 0
Views: 366
Reputation: 791
You can use .dt.strftime
for string formatting of the Timestamp
>>> df1.date.dt.strftime("%Y-%m-%dT%TZ")
0 2021-02-09T12:03:40Z
Name: date, dtype: object
Upvotes: 2