1

Im New to Python, it sounds easy- but i cant solve it, nether find a resolution with similar questions.

I have an Array where every row has one value ((...), Hour, Min., Sec., (...) ,D, M, Y) - Example:

arr = np.array([x, x,0, 0, 3, x, x,10, 8, 2022])

How can I conect the rows by ID to create an Data.frame of Date and Time in the formate:

Date:              Time:
YY/DD/MM           HH:MM:SS

So in my example i want to create an dataframe like:

Date:              Time:
2022/08/10         00:00:03

I was trying to use merge or concat, but only reach to the output:

[2022.10.8],[0.0.3]

High Thanks for any ideas! : )

MaryJule
  • 23
  • 5

1 Answers1

1

Try:

arr = np.array([-1, -1, 0, 0, 3, -1, -1, 10, 8, 2022])

df = pd.DataFrame(
    [
        pd.to_datetime(
            f"{arr[-1]}/{arr[-2]}/{arr[-3]} {arr[-8]}:{arr[-7]}:{arr[-6]}"
        )
    ],
    columns=["DateTime"],
)

df["Date"] = df["DateTime"].dt.strftime("%Y/%m/%d")
df["Time"] = df["DateTime"].dt.time
df = df[["Date", "Time"]]

print(df)

Prints:

         Date      Time
0  2022/08/10  00:00:03
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • Hey Andrej, looks so easy and obvious now, thank you! – MaryJule Nov 30 '22 at 12:38
  • But one question: is there a reason why you first created them into one column ("DateTime") and then separated it, instead of creating directly two columns like columns=["Date", "Time"] ? – MaryJule Nov 30 '22 at 13:02
  • 1
    @MaryJule I use the function `pd.to_datetime` - this function also checks if the date/time is correct. Also, when you have datetime object you can use various function (using the `.dt` accessor) which is convenient. – Andrej Kesely Nov 30 '22 at 13:14