Commit f9e5f936 authored by Cresson Remi's avatar Cresson Remi
Browse files

ADD: module dates

1 merge request!23Add deepnets
Showing with 45 additions and 0 deletions
+45 -0
# -*- coding: utf-8 -*-
"""
This module aims to deal with dates
"""
import datetime
def str2datetime(datestr):
"""
Converts an input date as string into a datetime instance.
Args:
datestr: date (str) in the format "YYYY-MM-DD" or "DD/MM/YYYY" or "DD-MM-YYYY"
Returns:
A datetime.datetime instance
"""
# source (with a few enhancements):
# https://stackoverflow.com/questions/23581128/how-to-format-date-string-via-multiple-formats-in-python
assert isinstance(str, datestr), "Input must be a str!"
formats = ('%Y-%m-%d', '%d/%m/%Y', '%d-%m-%Y')
for fmt in formats:
try:
return datetime.datetime.strptime(datestr, fmt)
except ValueError:
pass
raise ValueError(f'No valid date format found. Accepted formats are {formats}. Input was: {datestr}')
def any2datetime(str_or_datetime):
"""
Normalizes the input such as the returned object is a datetime.datetime instance.
Args:
str_or_datetime: a str (see `str2datetime()` for supported dates formats) or a datetime.datetime
Returns:
A datetime.datetime instance
"""
if isinstance(datetime.datetime, str_or_datetime):
return str_or_datetime
assert isinstance(str, str_or_datetime), "Date must be a str, or a datetime.datetime instance!"
return dates.str2datetime(str_or_datetime)
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment