search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

R lubridate ymd Function in Python, Convert Integer To Date | ARON HACK 亞倫害的

目錄

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.〉

Content Protection by DMCA.com
A
Aron

Data analyst, but building WordPress websites, having experience in digital marketing. Recently dives into fighting and Python quantitative investment.



熱門推薦

本文由 aronhackcom 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦