#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Time utilities
"""
import logging
import numpy as np
import pandas as pd
LOGGER = logging.getLogger(__name__)
[docs]def convert_to_julian_day(time):
"""Conversion of date in Julian day"
Parameters
----------
time
Output
------
xr.Dataset
"""
LOGGER.info("Convert time to julian day")
return (time - np.datetime64("1950-01-01")) / np.timedelta64(1, "D")
[docs]def convert_from_julian_day(time, unit='D'):
"""Conversion of Julian day in date"
Parameters
----------
time
Output
------
xr.Dataset
"""
LOGGER.info("Convert julian day to time")
res = np.timedelta64(int(time), unit) + np.datetime64("1950-01-01")
return res
[docs]def find_monday(date):
"""Find the lastest monday
Parameters
----------
date: string format
Output
------
date of the latest monday in string format
"""
date = pd.to_datetime(date)
monday = date - pd.to_timedelta(date.dayofweek, "D")
return monday.strftime("%Y%m%d")
[docs]def running_time(start=None, maxterm=None, step=None):
"""Build the list of running dates
Parameters
----------
start: starting date
maxterm: maximum term
step: time step
Output
------
list of running dates
"""
step = period_vortex_to_pandas(step)
end = pd.to_datetime(start)+pd.to_timedelta(maxterm)
time = pd.date_range(start=start, end=end.strftime('%Y%m%d%H%M'),
freq=step)
return list(time)
[docs]def period_vortex_to_pandas(period):
"""Convert a vortex period string to a pandas period string
For pandas, see : https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases
"""
if period.startswith("PT"):
if period.endswith("M"):
period = period.replace('M', 'min')
period = period[2:]
elif period.startswith("P"):
period = period[1:]
return period