3C科技 娛樂遊戲 美食旅遊 時尚美妝 親子育兒 生活休閒 金融理財 健康運動 寰宇綜合

Zi 字媒體

2017-07-25T20:27:27+00:00
加入好友
目錄 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 reresults = re.sub('[^a-zA-Z0-9 \n\.]', value, string) return resultsdef 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 Aron Data analyst, but building WordPress websites, having experience in digital marketing. Recently dives into fighting and Python quantitative investment.

本文由aronhackcom提供 原文連結

寫了 5860316篇文章,獲得 23313次喜歡
精彩推薦