0

I have a two million timestamp data. I am trying to find first and last date that to in the YYYY-MM-DD format so I can use them in saving file name. But, I found out that np.unique(df.index) is fast (10s) and produces dates in the datetime.date(2022, 6, 7) format but df.index.strftime('%Y-%m-%d').unique() gives the output I want but it takes more than 5 min, which is bad. So, I decided to use the former approach.

So, How do I convert something like datetime.date(2022, 6, 7) to'2022-06-07'?

Mainland
  • 4,110
  • 3
  • 25
  • 56

2 Answers2

1

Just put that into the str(...) function:

import datetime
my_date = datetime.date(2022, 6, 7)
print(str(my_date))  # prints 2022-06-07

Technically, you can just print it and not make it a string first. But putting it in str means that instead of printing it, you could save that string to a variable.

If you need more advanced formatting options, then you can do what @FObersteiner suggested. But the format you want happens to be the default, so this will do if you just want that one format

cocomac
  • 518
  • 3
  • 9
  • 21
1

Try this:

# import datetime module
from datetime import datetime
  
# consider date in string format
my_date = "30-May-2020-15:59:02"
  
# convert datetime string into date,month,day and
# hours:minutes:and seconds format using strptime
d = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S")
  
# convert datetime format into %Y-%m-%d-%H:%M:%S
# format using strftime
print(d.strftime("%Y-%m-%d-%H:%M:%S"))