Skip to content
Snippets Groups Projects
input_toolbox.py 1.28 KiB
# -*- coding: UTF-8 -*-
# Python
"""
Contains functions to facilitate code workflow, directory creation, Notebook readability, logfile creation, etc.
04-07-2023
@author: jeremy auclair
"""

import re  # for character string search
import datetime  # for date management


def product_str_to_datetime(product_name: str) -> datetime.date:
    """
    product_str_to_datetime returns a `datetime.date` object for the date of the given product.
    Works for both copernicus and theia providers.

    ## Arguments
    1. product_name: `str `
        name or path of the product

    ## Returns
    1. product_date: `datetime.date`
        datetime.date object, date of the product
    """

    # Search for a date pattern (yyyymmdd) in the product name or path
    try:
        match = re.search('\d{4}\d{2}\d{2}', product_name)
        format = '%Y%m%d'
        datetime_object = datetime.datetime.strptime(match[0], format)
        return datetime_object.date()
    except TypeError:
        pass
    
    # Search for a date pattern (yymmdd) in the product name or path
    try:
        match = re.search('\d{2}\d{2}\d{2}', product_name)
        format = '%y%m%d'
        datetime_object = datetime.datetime.strptime(match[0], format)
        return datetime_object.date()
    except TypeError:
        pass