R lubridate ymd Function in Python, Convert Integer To Date


Original Posts

〈R lubridate ymd Function in Python, Convert Integer To Date〉


So many Python programmers complained about the inconvenience of datetime package. It’s not easy to use like ymd function of lubridate library in R, which can directly convert an integer to a date object, like 20200101 to 2020-0101. Though there are some improved packages to deal with date and time, ie.arrow. However, I don’t think it’s a good way to import bulk libraries to projects even not necessary. In my opinion, I prefer to build some custom functions based on common packages like datetime. You can refer to the other post 〈Import Custom Package/Library/Module In Python〉.

Copy, Paste, And Work

def str_replace_special(string, value=''):
Remove special characters.
import re
results = re.sub('[^a-zA-Z0-9 \n\.]', value, string)

return results

def ymd(series):
Convert integer to date.
if isinstance(series, str):
series = str_replace_special(series)

if isinstance(series, int) | isinstance(series, str):
series = str(series)
series = datetime.datetime(year = int(series[0:4]),
month = int(series[4:6]),
day = int(series[6:8]))

return series

In contrast, I use the function below to convert date object to integer to save memory.

def simplify_date(obj):
    import datetime
    if isinstance(obj, int):
        return obj
    if (isinstance(obj, datetime.datetime)) or (isinstance(obj, datetime.date)):
        obj = obj.strftime('%Y%m%d')
    if isinstance(obj, str):
        obj = str_replace_special(obj)
    obj = int(obj)
    return obj

Related Posts

〈Learn Python And R On DataCamp. Start Your Data Science Career.〉

A data scientist working in a retail company, with experience in web design and marketing. Recently dives into cryptocurrency and quantitative investing.