《Python学习:python time模块之time.strptime()》
《python 中的[:-1]和[::-1]的具体使用》
《[1:3] python符号表示什么意思??》
《python错误embedded null character》
《re.match()使用方法详解与实战应用》
import time
import os
import re
from osgeo import gdal
import numpy as np
def info_general_metadata(filename):
"""
This function retrieves general information of the Landsat image
(date and time aquired, UTM zone, sun elevation) from the
metadata file.
该函数检索陆地卫星图像的一般信息(获取的日期和时间、UTM区域、太阳高度)元数据文件。
"""
Landsat_meta = open(filename, "r") # Open metadata file 打开元数据文件
for line in Landsat_meta:
if re.match("(.*)SCENE_CENTER_TIME(.*)", line): # 从字符串的开始位置进行匹配,如果起始位置匹配成功,则返回Match对象search in metadata for line SCENE_CENTER_TIME
words = line.split()# make groups of words which are divided by an open space 用一个开放的空间将单词分组
time_list = words[2].split(':', 2) # Take the second word of words and split the word which are divided by : 取单词中的第二个单词,用:分隔
if len(time_list[0])== 3: #为了确保这个时间是按照时分秒来登记的
time_list[0]=time_list[0][1:3] #下标是以0开始的 x[1:3]表示返回集合中下标1至3(不包括3)的元素集合
print(time_list[0])
time_list[2]=time_list[2][0:-1] #左起第一个元素到最后一个元素,不包括最后一个元素
print(time_list[2])
hour = float(time_list[0]) # take the first word of time_list #小时
minutes = float(time_list[1]) + float(time_list[2][:-1]) / 60 # [:1]从位置0到位置-1之前的数Take the second and third word of time_list and place :-1 to remove Z behined minutes
Landsat_meta = open(filename, "r") # Open metadata file
for line in Landsat_meta:
if re.match("(.*)DATE_ACQUIRED(.*)", line): #DATE_ACQUIRED=2021-01-18
words = line.split() #根据空格进行分割
# 根据指定的格式把一个时间字符串解析为时间元组
DOY = time.strptime(words[2], "%Y-%m-%d").tm_yday #这天是这年的第几天
year = time.strptime(words[2], "%Y-%m-%d").tm_year #这年
Landsat_meta = open(filename, "r") # Open metadata file
for line in Landsat_meta:
if re.match("(.*)UTM_ZONE(.*)", line):
words = line.split()
UTM_Zone = int(words[2]) #获取UTM条带号
Landsat_meta = open(filename, "r") # Open metadata file
for line in Landsat_meta:
if re.match("(.*)SUN_ELEVATION(.*)", line):
words = line.split()
Sun_elevation = float(words[2]) #获取太阳高度
return year, DOY, hour, minutes, UTM_Zone, Sun_elevation
file="D:\\DATA\\SEBAL\\0. InitialData\\LC81310392021018LGN00\\LC08_L1TP_131039_20210118_20210306_01_T1_MTL.txt"
year, DOY, hour, minutes, UTM_Zone, Sun_elevation=info_general_metadata(file)