-2

I have a file which is in hdf format. I want to extract date from the file name? how can I do that using Python 2.7??

i have tried using split command and also regex but not working

My filename looks like this:

CAL_LID_L2_05kmAlay-Standard-V4-20.2012-08-01T06-24-24.hdf
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Sreerag Ek
  • 13
  • 3

1 Answers1

0

You need to split() your filename into parts and parse the datetime part from it using datetime.strptime():

fn = "CAL_LID_L2_05kmAlay-Standard-V4-20.2012-08-01T06-24-24.hdf"

import datetime

dt_str = fn.split(".")[-2]  # split out the datetime part

# parse the datetime 
dt = datetime.datetime.strptime(dt_str, "%Y-%m-%dT%H-%M-%S")

print(dt_str)
print(dt)
print(dt.date())

Output:

2012-08-01T06-24-24   # the cutout string
2012-08-01 06:24:24   # the datetime object
2012-08-01            # only the date()

Doku:

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • my filename is CAL_LID_L2_05kmALay-Standard-V4-20.2018-01-04T18-49-46ZN.hdf – Sreerag Ek May 06 '19 at 15:54
  • @Sre Why did you leave out the ZN in your code then?!? Use `dt_str = fn.split(".")[-2].rstrip("ZN")` – Patrick Artner May 06 '19 at 15:55
  • now the format is in datetime.data . Can i add it to a coulmn in excel sheet with dat month year separately – Sreerag Ek May 06 '19 at 16:05
  • @Sree why dont you look it up? Tried the documentation already? datetime objects have methods to get year, month, day, hour, minute and second from it: https://docs.python.org/3/library/datetime.html#available-types – Patrick Artner May 06 '19 at 18:55