How to use .split() to extract HH,MM,SS separately from a 1970-1-1T00:00:00Z and get "00" instead of "0"

Question:

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?

Asked By: linux_lover

||

Answers:

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)
Answered By: Michael M.

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.
Answered By: I'mahdi
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.