![]() |
How to get datetime from numeric format field - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to get datetime from numeric format field (/thread-35440.html) |
How to get datetime from numeric format field - klllmmm - Nov-03-2021 Hi there, Can someone help me to extract datetime from the following "data" field import pandas as pd import datetime as dt df1 = pd.DataFrame(data={"fruit":['apple','pear','banana','peach'], 'id':[2,1,3,4], 'Data':['20210522113347','20210522113359','20210522113412','20210522113431']}) df1['Data1'] = pd.to_datetime((df1['Data'])).dt.strftime('%Y%M%D%H%M%S') Appreciate it if someone can help.
RE: How to get datetime from numeric format field - deanhystad - Nov-05-2021 What are you trying to do? This will give you a column of datetime objects. df1['Data1'] = pd.to_datetime((df1['Data']))Now that you have a datetime object you can convert it back to a string. I like to format dates like Nov 5, 2021. import pandas as pd import datetime as dt df = pd.DataFrame(data={"fruit":['apple','pear','banana','peach'], 'id':[2,1,3,4], 'Date':['20201221113347','20211103113359','20211103113412','20211105113431']}) df['Data1'] = pd.to_datetime((df['Date'])).dt.strftime('%b %d, %Y') print(df) Note: I changed some of your dates . Better toss the apples!A description of format characters for datetime.strftime: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior If you want to extract info like the day, month, year etc from the datetime: https://docs.python.org/3/library/datetime.html#datetime-objects RE: How to get datetime from numeric format field - klllmmm - Nov-06-2021 Thanks!! @deanhystad RE: How to get datetime from numeric format field - snippsat - Nov-06-2021 As info so dos Pandas has Time/date functionality build in. So no need for this import import datetime as dt import pandas as pd df1 = pd.DataFrame( data={ "fruit": ["apple", "pear", "banana", "peach"], "id": [2, 1, 3, 4], "Data": [ "20210522113347", "20210522113359", "20210522113412", "20210522113431", ], } ) df1['Data'] = pd.to_datetime(df1['Data']) >>> df1 fruit id Data 0 apple 2 2021-05-22 11:33:47 1 pear 1 2021-05-22 11:33:59 2 banana 3 2021-05-22 11:34:12 3 peach 4 2021-05-22 11:34:31 >>> df1.Data.dt.strftime('%m/%d/%Y') 0 05/22/2021 1 05/22/2021 2 05/22/2021 3 05/22/2021 Name: Data, dtype: object >>> #Save DataFrame with a new date format >>> df1['Data'] = df1.Data.dt.strftime('%b %d, %Y') >>> df1 fruit id Data 0 apple 2 May 22, 2021 1 pear 1 May 22, 2021 2 banana 3 May 22, 2021 3 peach 4 May 22, 2021 |