{ "cells": [ { "cell_type": "markdown", "id": "948d7cae-39ae-4cab-8eee-8726af623727", "metadata": { "tags": [] }, "source": [ "# **Datetime**\n", "## **1 Datetime Object**" ] }, { "cell_type": "code", "execution_count": 29, "id": "1f6ee828-a2bb-46ba-a376-d005328b18cf", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'2002-08-02'" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import re\n", "_date = \"\".join(re.findall(r'[\\d]{8}', '20020802'))\n", "_date = f\"{_date[:4]}-{_date[4:6]}-{_date[6:]}\"\n", "_date" ] }, { "cell_type": "code", "execution_count": 51, "id": "91d7b965-9353-4a8f-b3ae-c0ec6764a0a8", "metadata": {}, "outputs": [], "source": [ "import re\n", "import datetime\n", "def date_to_string(_date:any=None, datetime_obj:bool=False):\n", " r\"\"\"date 객체를 string 으로 자동변환\n", " _date : 날짜객체\n", " datetime : datetime 객체로 출력\n", " return :: '2000-01-01'\"\"\"\n", " _return = None\n", " if type(_date) == datetime.date:\n", " _return = _date.isoformat()\n", " elif type(_date) == datetime.datetime:\n", " _return = _date.date()\n", " elif type(_date) == str:\n", " # '20020802'\n", " _check = \"\".join(re.findall(r'[\\d]{8}', _date))\n", " if len(_check) == 8:\n", " _return = f\"{_check[:4]}-{_check[4:6]}-{_check[6:]}\"\n", " \n", " for punct_string in ['-','/',',', '.']:\n", " if _date.find(punct_string) != -1:\n", " _return = \"-\".join(list(map(lambda x : (f'{x:0>2}'), _date.split(punct_string))))\n", " else:\n", " pass\n", "\n", " assert _return is not None, f'TypeError : {_date} 를 분석할 수 없습니다'\n", " if datetime_obj:\n", " # datetime.datetime.strptime('09/19/22 13:55:26', '%m/%d/%y %H:%M:%S')\n", " return datetime.datetime.strptime(_return, '%Y-%m-%d')\n", " return _return" ] }, { "cell_type": "code", "execution_count": 54, "id": "2eb50909-b5a5-4d48-ad67-5ea5b7a53c71", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'2022-01-01'" ] }, "execution_count": 54, "metadata": {}, "output_type": "execute_result" } ], "source": [ "_ = datetime.date.today()\n", "_ = '20220101'\n", "date_to_string(_)" ] }, { "cell_type": "markdown", "id": "0cf4596c-d59c-407d-8a91-fa202a6d3449", "metadata": { "tags": [] }, "source": [ "# **Django ORM Datetime**\n", "- 일반적 ORM 객체등은 원칙적 **datetime.dateime** 객체이다 \n", "- **datetime.date** 객체로만 관리되면 문제가 없지만\n", "- **datetime.datetime** 에서 **date** 만 활용하는 경우에도 시간대가 다르면 날짜도 다르게 출력\n", "- **Pandas Datetime Index 객체** 는 추가적 편리한 메소드들을 제공\n", "\n", "## **1 tzinfo Convert : datetime**" ] }, { "cell_type": "code", "execution_count": 1, "id": "11357004-d020-4d08-9626-b9e8e3402a91", "metadata": {}, "outputs": [], "source": [ "# Django ORM 데이터 tz_info 변경 및 확인\n", "# Django DateTime => datetime.datetime 객체를 출력\n", "import pytz\n", "seoul = pytz.timezone(\"Asia/Seoul\")\n", "# time_check = PriceKRX.objects.all().last().datetime\n", "# time_check.replace(tzinfo=seoul)" ] }, { "cell_type": "markdown", "id": "4fb239b5-104c-46ff-ad52-7df189f32d75", "metadata": { "tags": [] }, "source": [ "## **2 tzinfo Convert : pd.DataFrame**" ] }, { "cell_type": "code", "execution_count": 2, "id": "4b4203ab-5826-4253-8ac1-827861bbd117", "metadata": {}, "outputs": [], "source": [ "# DataFrame 의 tz_info 변경\n", "import pytz\n", "import pandas as pd\n", "seoul = pytz.timezone(\"Asia/Seoul\")\n", "# df.datetime = list(map(\n", "# lambda x : seoul.localize(x), \n", "# df.datetime.tolist())\n", "# )" ] }, { "cell_type": "code", "execution_count": 3, "id": "ec1d402e-7a82-4905-a1dc-14b996694168", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/home/buffet/Coding/venv/Nlp/lib/python3.10/site-packages/krxstock/shinhan/data.py:51: FutureWarning: In a future version, `df.iloc[:, i] = newvals` will attempt to set the values inplace instead of always setting a new array. To retain the old behavior, use either `df[df.columns[i]] = newvals` or, if columns are non-unique, `df.isetitem(i, newvals)`\n", " df.loc[:,'수량'] = list(map(lambda x : int(x)*(-1), df.loc[:,'수량']))\n", "/home/buffet/Coding/venv/Nlp/lib/python3.10/site-packages/krxstock/shinhan/data.py:51: FutureWarning: In a future version, `df.iloc[:, i] = newvals` will attempt to set the values inplace instead of always setting a new array. To retain the old behavior, use either `df[df.columns[i]] = newvals` or, if columns are non-unique, `df.isetitem(i, newvals)`\n", " df.loc[:,'수량'] = list(map(lambda x : int(x)*(-1), df.loc[:,'수량']))\n", "/home/buffet/Coding/venv/Nlp/lib/python3.10/site-packages/krxstock/shinhan/data.py:78: FutureWarning: In a future version, `df.iloc[:, i] = newvals` will attempt to set the values inplace instead of always setting a new array. To retain the old behavior, use either `df[df.columns[i]] = newvals` or, if columns are non-unique, `df.isetitem(i, newvals)`\n", " df.loc[:,'비중'] = list(map(lambda x : float(x.replace('%',''))/100, df.loc[:,'비중']))\n", "/home/buffet/Coding/venv/Nlp/lib/python3.10/site-packages/krxstock/shinhan/data.py:80: FutureWarning: In a future version, `df.iloc[:, i] = newvals` will attempt to set the values inplace instead of always setting a new array. To retain the old behavior, use either `df[df.columns[i]] = newvals` or, if columns are non-unique, `df.isetitem(i, newvals)`\n", " df.loc[:,'시간'] = pd.DatetimeIndex(df.loc[:,'시간'])\n" ] }, { "data": { "text/plain": [ "Timestamp('2023-03-30 15:30:00+0900', tz='Asia/Seoul')" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pytz\n", "from krxstock.shinhan import get_invest\n", "seoul = pytz.timezone(\"Asia/Seoul\")\n", "df = get_invest(\"005930\")\n", "df[\"시간\"][0].replace(tzinfo=seoul)\n", "\n", "# from krx.tasks import get_trading_invest\n", "# get_trading_invest()" ] }, { "cell_type": "code", "execution_count": 6, "id": "fa65479c-8b5e-434e-a282-c4e9a164416a", "metadata": {}, "outputs": [], "source": [ "# from glob import glob\n", "# from krx.tasks import get_trader_price\n", "# # files = glob(\"../jupyter/data/trade/csv/*.*\")\n", "# # get_trader_price(files[0])" ] }, { "cell_type": "markdown", "id": "bd61cee2-5c9f-455a-abd7-085e04e42170", "metadata": { "tags": [] }, "source": [ "# **Python Datetime**\n", "## **1 tzinfo Convert : datetime**" ] }, { "cell_type": "code", "execution_count": 7, "id": "8a6cad02-6516-4532-a17c-8e3fb0a99af7", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "06/12/2018, 18:55:22\n", "12 Jun, 2018\n", "12 June, 2018\n" ] } ], "source": [ "import datetime\n", "timestamp = 1528797322\n", "date_time = datetime.datetime.fromtimestamp(timestamp)\n", "print( date_time.strftime(\"%m/%d/%Y, %H:%M:%S\") )\n", "print( date_time.strftime(\"%d %b, %Y\") )\n", "print( date_time.strftime(\"%d %B, %Y\") )" ] }, { "cell_type": "code", "execution_count": 8, "id": "c2b0a144-6548-4bdd-a250-6c192b8786a8", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2023-03-30\n", "2000-01-01 00:00:00\n", "2018-09-19 13:55:26\n" ] }, { "data": { "text/plain": [ "datetime.datetime(2023, 3, 23, 9, 54, 38, 820579)" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# datetime 모듈의 활용\n", "import datetime\n", "print( datetime.datetime.today().strftime('%Y-%m-%d') )\n", "print( datetime.datetime(year=2000, month=1, day=1) )\n", "print( datetime.datetime.strptime('09/19/18 13:55:26', '%m/%d/%y %H:%M:%S') )\n", "datetime.datetime.today() - datetime.timedelta(days=7)" ] }, { "cell_type": "code", "execution_count": 9, "id": "8a8b9321-75c2-4c36-9710-2843325bf893", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "datetime.datetime(2018, 5, 1, 0, 0)" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from datetime import datetime\n", "dateString = \"7-May-2018\"\n", "dateFormatter = \"%u-%b-%Y\"\n", "datetime.strptime(dateString, dateFormatter)" ] }, { "cell_type": "code", "execution_count": 10, "id": "81de2e7e-8afb-4253-abac-faff5bb3e6a3", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'2019-12-13 00:00'" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "time_text = '2019.12.13.AM 00:00'\n", "import pandas as pd\n", "pd.to_datetime(time_text, format='%Y.%m.%d.%p %H:%M').strftime('%Y-%m-%d %H:%M')" ] }, { "cell_type": "markdown", "id": "ab376e6a-146f-44c1-8a03-7a2fa2809b15", "metadata": {}, "source": [ "## **2 Lambda**" ] }, { "cell_type": "code", "execution_count": 11, "id": "d684a414-7f7a-42eb-b84b-b307411df798", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "False\n", "False\n" ] }, { "data": { "text/plain": [ "['ok', None, None]" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Check if given numbers are in range using lambda function\n", "test = lambda x : True if (x > 10 and x < 20) else False\n", "print(test(12))\n", "print(test(3))\n", "print(test(24))\n", "\n", "# https://thispointer.com/python-how-to-use-if-else-elif-in-lambda-functions/\n", "# https://stackoverflow.com/questions/60261960/how-to-use-lambda-if-else-in-map-on-list-in-python\n", "list(map(lambda x : 'ok' if x == \"apple\" else None, ['apple', 'banana', 'cherry']))" ] }, { "cell_type": "code", "execution_count": 12, "id": "0a3d37ae-9ed5-4a73-b874-72ffb1586792", "metadata": {}, "outputs": [], "source": [ "test = {\n", " \"A\":1,\n", " \"B\":2,\n", "}" ] }, { "cell_type": "code", "execution_count": 13, "id": "ddc194f3-7d57-4a3d-ab61-47dcc0b242ba", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "test.get(\"d\", 10)" ] }, { "cell_type": "code", "execution_count": 14, "id": "5c6763eb-0dc8-4348-9bbc-2e6733c13b19", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'A': 1, 'B': 2}" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "test" ] }, { "cell_type": "code", "execution_count": null, "id": "331cbb4e-e9b8-47b7-9a5a-4c667c63ad1e", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.5" } }, "nbformat": 4, "nbformat_minor": 5 }