英文:
How to use .split() to extract HH,MM,SS separately from a 1970-1-1T00:00:00Z and get "00" instead of "0"
问题
我有一个包含时间格式为1970-1-1T00:00:00Z
的netcdf文件。我需要使用split()
提取小时、分钟和秒。我尝试如下,但结果不如预期。
hour = int(nc['time'].units.split(' ')[2].split('-')[2][8])
print(hour)
0
有人有解决方法吗?
英文:
I have a netcdf file containing time in the format 1970-1-1T00:00:00Z
. I need to extract the hour, minute and seconds using split()
. I tried as follows, but it didn't work as expected.
hour = int(nc['time'].units.split(' ')[2].split('-')[2][8])
print(hour)
0
Does anybody have a solution to do this?
答案1
得分: 1
你可以首先按'T'
拆分以获取时间部分,然后再按:
拆分以获取小时、分钟和秒钟:
t = '1970-1-1T00:00:00Z'
(hour, minute, seconds) = t.split('Z')[0].split('T')[1].split(':')
print(hour, minute, seconds)
或者,你可以使用正则表达式:
import re
t = '1970-1-1T00:00:00Z'
(hour, minute, seconds) = re.findall(r'T(\d{2}):(\d{2}):(\d{2})', t)[0]
print(hour, minute, seconds)
英文:
You can first split by the 'T'
to get the time part, then split again by the :
to get the hours, minutes, and seconds:
t = '1970-1-1T00:00:00Z'
(hour, minute, seconds) = t.split('Z')[0].split('T')[1].split(':')
print(hour, minute, seconds)
Alternatively, you can use a regular expression:
import re
t = '1970-1-1T00:00:00Z'
(hour, minute, seconds) = re.findall(r'T(\d{2}):(\d{2}):(\d{2})', t)[0]
print(hour, minute, seconds)
答案2
得分: 0
你可以在使用 str.split
之前使用 str.replace
。
>>> "1970-1-1T00:00:00Z".replace('Z', '').split('T')[1].split(':')
['00', '00', '00']
你可以使用 re.findall
。
h, m, s = re.findall(r"T(\d+):(\d+):(\d+).*$", "1970-1-1T00:00:00Z")[0]
print(h, m, s)
# 00 00 00
解释:
T
匹配字符"T"
。(\d+)
是一个捕获组,匹配一个或多个数字。:
匹配字符":"
。.*
匹配零个或多个任意字符。$
匹配行尾。
英文:
You can use str.replace
before using str.split
.
>>> "1970-1-1T00:00:00Z".replace('Z', '').split('T')[1].split(':')
['00', '00', '00']
You can re.findall
.
h, m, s = re.findall(r"T(\d+):(\d+):(\d+).*$", "1970-1-1T00:00:00Z")[0]
print(h, m, s)
# 00 00 00
Explanation:
T
matches the character"T"
.(\d+)
is a capturing group that matches one or more digits.:
matches the character":"
..*
matches zero or more of any character.$
matches the end of the line.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论