Python Forum

Full Version: How to get datetime from numeric format field
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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')
Output:
fruit id Data Data1 0 apple 2 20210522113347 20213305/22/21113347 1 pear 1 20210522113359 20213305/22/21113359 2 banana 3 20210522113412 20213405/22/21113412 3 peach 4 20210522113431 20213405/22/21113431
Appreciate it if someone can help.
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)
Output:
fruit id Date Data1 0 apple 2 20201221113347 Dec 21, 2020 1 pear 1 20211103113359 Nov 03, 2021 2 banana 3 20211103113412 Nov 03, 2021 3 peach 4 20211105113431 Nov 05, 2021
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/dateti...e-behavior

If you want to extract info like the day, month, year etc from the datetime:

https://docs.python.org/3/library/dateti...me-objects
Thanks!! @deanhystad
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