[AstroPy] Time custom formats

Aldcroft, Thomas aldcroft at head.cfa.harvard.edu
Mon Feb 22 07:07:48 EST 2016


Hi Paul,

What you want is exactly a custom format, and in this case it's quite easy
to get both input and output representation in the format you want.  This
is just copied from the existing TimeYearDayTime class and modified
slightly.  When you define the class like this it is automatically
registered as an available format like the rest, including automatic input
parsing when possible.

from astropy.time import TimeISO

class TimeYearDayTimeCustom(TimeISO):
    """
    Year, day-of-year and time as "<YYYY>-<DOY>T<HH>:<MM>:<SS.sss...>".
    The day-of-year (DOY) goes from 001 to 365 (366 in leap years).
    For example, 2000-001T00:00:00.000 is midnight on January 1, 2000.
    The allowed subformats are:
    - 'date_hms': date + hours, mins, secs (and optional fractional secs)
    - 'date_hm': date + hours, mins
    - 'date': date
    """

    name = 'yday_custom'
    subfmts = (('date_hms',
                '%Y-%jT%H:%M:%S',
                '{year:d}-{yday:03d}T{hour:02d}:{min:02d}:{sec:02d}'),
               ('date_hm',
                '%Y-%jT%H:%M',
                '{year:d}-{yday:03d}T{hour:02d}:{min:02d}'),
               ('date',
                '%Y-%j',
                '{year:d}-{yday:03d}'))

In [4]: t = Time.now()

In [5]: t.yday_custom
Out[5]: '2016-053T12:01:41.663'

In [6]: t2 = Time('2016-001T00:00:00')

In [7]: t2.iso
Out[7]: '2016-01-01 00:00:00.000'

- Tom





On Fri, Feb 19, 2016 at 8:51 AM, Paul Ray <paul.ray at nrl.navy.mil> wrote:

> Hi,
>
> I've been trying to figure out how to print an astropy.Time with a custom
> string format and have not been able to.
>
> In [2]: t = astropy.time.Time.now()
>
> In [3]: t.yday
> Out[3]: '2016:050:13:45:21.260'
>
> Now, what if I want the string '2016-050T13:45:21' instead?
> What I'd like is basically the astropy equivalent of the C library
> strftime().
>
> I see there is a way to make a new subclass of TimeFormat, but I don't
> really want a whole new format, just a way to customize the string
> representation (possibly for input as well as output).  Maybe all I need is
> an example of how to subclass TimeFormat to accomplish that. I had some
> trouble getting it to work in the little experimenting I did.
>
> Thanks for any tips,
>
> -- Paul
>
>
> _______________________________________________
> AstroPy mailing list
> AstroPy at scipy.org
> https://mail.scipy.org/mailman/listinfo/astropy
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/astropy/attachments/20160222/8b73b248/attachment.html>


More information about the AstroPy mailing list