planetarypy / pvl

Python implementation of PVL (Parameter Value Language)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Can I force load() to store PVL keyword values as strings?

jcwbacker opened this issue · comments

Hi,
I am using your pvl.load() method to read in an ISIS cube label and extracting keyword values. Unfortunately for me, your software is smarter than I would like it to be. When the StartTime keyword is read in, it is recognized and saved as a datetime object. So, when I access the keyword value, the format might be returned slightly changed from what is originally in the label:

Label Example:
StartTime = 1971-07-31T14:02:28.186

Returned as
1971-07-31 14:02:28.186000

Notice the T is stripped and microseconds are reported instead of milliseconds.

For the project I am working on, I need to save the keyword values that I read in as strings so that I can get the exact values that are in the label. Is there currently a flag I can turn on/off to allow me to do this?
Thanks,
Jeannie

Hi Jeannie,

There's a couple possible solutions I can think of depending on what you want. If you just need the dates in iso format, the simplest solution would be to use the datetime isoformat method:

>>> import pvl
>>> data = """
...     StartTime = 1971-07-31T14:02:28.186
... """
>>> label = pvl.loads(data)
>>> label['StartTime'].isoformat()
'1971-07-31T14:02:28.186000'

If you actually want the original value for all dates you can also override the parse_datetime on the decoder class:

>>> import pvl
>>> from pvl.decoder import PVLDecoder
>>> class StringDatetimeDecoder(PVLDecoder):
...     def parse_datetime(self, value):
...         return value
>>> data = """
...     StartTime = 1971-07-31T14:02:28.186
... """
>>> label = pvl.loads(data, cls=StringDatetimeDecoder)
>>> label['StartTime']
'1971-07-31T14:02:28.186'

Similarly if you want the original value for all simple types, you can override cast_unquoated_string instead:

>>> import pvl
>>> from pvl.decoder import PVLDecoder
>>> class SimpleStringDecoder(PVLDecoder):
...     def cast_unquoated_string(self, value):
...         return value
>>> data = """
...     StartTime = 1971-07-31T14:02:28.186
... """
>>> label = pvl.loads(data, cls=SimpleStringDecoder)
>>> label['StartTime']
'1971-07-31T14:02:28.186'

Hope that helps,
Trevor

Thanks, Trevor.
Appreciate the quick response!

The simple string decoder example works for what I need. I realize there is not much to this subclass, but if you think that it might be useful to others, I could put in a pull request to add it to your library.