0

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()

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Its working. The VS CODE just does not recognizes the dt function and its not highlighted. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.