0

Using Python3, I have the following for loop that outputs a year followed by a day number as one figure. I want to be able to be able to convert this into a proper date. Please see below the code and what I am trying to achieve.

from datetime import datetime
import os
import rasterio

for filename in sorted(os.listdir(output_dir)):
    f = os.path.join(output_dir, filename)
    # checking if it is a file
    if os.path.isfile(f):
        #print(filename)
        with rasterio.open(f) as clipped:
            import re
            x_title = re.findall('\d+', filename)[0]
            date_object = datetime.strptime(x_title, "%Y%j")
            print(date_object)

When I run this code I get something like 2022-04-05 00:00:00 for the variable date_object which is close to what I want but there are two issues. First, there are the hours, minutes and seconds values showing up which I do not need, and second, I would then like to convert the date into a proper date such as "April 5 2022" rather than "2022-04-05".

Perhaps my lack of knowledge of the datetime module is the root cause but at this point I could use a hand. Thanks again.

4
  • 2
    Does this answer your question? Commented Oct 18, 2023 at 16:22
  • Hi thanks Maria. I did make a small change to my code which gets me closer as noted above in the altered explanation, but i have two problems..1st, the Hours, Minutes and Seconds values are all zeros and really unnecessary so I would like to print the variable date-object without the useless hours, minutes and seconds, and then I would like to change the actual date from the 2022-04-5 to print as "April 5 2022" Thanks for the help. Commented Oct 18, 2023 at 17:07
  • Onco you have a datetime you can format it how you like. I added a second duplicate which presents some options. Commented Oct 18, 2023 at 17:22
  • Try date = datetime(year, 1, 1) + timedelta(days) and then datetime.strftime(date,"%d %B %Y"). %B is for full month name. Here are all the codes. Commented Oct 18, 2023 at 17:22

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.