Skip to content

Instantly share code, notes, and snippets.

@maxcraftsman
Last active July 20, 2020 05:01
Show Gist options
  • Save maxcraftsman/ef170393eb151b75b23312cf29b81734 to your computer and use it in GitHub Desktop.
Save maxcraftsman/ef170393eb151b75b23312cf29b81734 to your computer and use it in GitHub Desktop.
Python cookbook
from datetime import date, datetime, timedelta
from calendar import monthrange
import pytz
dateRange = []
curTime = datetime.now()
def generateRange(start,end):
for y in range(start,end):
for m in range(1,13):
datestr_start = '{}-{}-{}'.format(y,m,1)
datestr_end = '{}-{}-{}'.format(y,m,monthrange(y, m)[1])
dateformat = datetime.strptime(datestr_end, "%Y-%m-%d")
if dateformat < curTime:
dateRange.append([datestr_start,datestr_end])
generateRange(2020,2021)
print(dateRange)
#Save pandas to sqlite [dirty]
import pandas as pd
import sqlalchemy as sa
e = sa.create_engine(r'sqlite:////path/to/file/database.db', echo=True) # LINUX
e = sa.create_engine(r'sqlite:///C:\\path\\to\\database.db', echo=True) # WINDOWS
df.to_sql("deskykt", e, if_exists="append", index=False)
#Example of date column replace by function and change depending of the conditions [dirty]
import csv
import pandas as pd
import shutil
import pymysql
import sys
import re
from urllib.request import urlopen
from bs4 import BeautifulSoup
import sqlalchemy as sa
import pytz
from datetime import date, time, datetime, timedelta
timenow = datetime.now(pytz.timezone('Asia/Tokyo'))
timeyesterday = timenow - timedelta(days=1)
datenow = timenow.strftime('%d.%m.%Y')
dateyesterday = timeyesterday.strftime('%d.%m.%Y')
dnstr = datetime.strptime(datenow, '%d.%m.%Y')
def time_converter(get_val, pastdate):
RU_MONTH_VALUES = {
'янв': 1,
'фев': 2,
'мар': 3,
'апр': 4,
'мая': 5,
'июн': 6,
'июл': 7,
'авг': 8,
'сен': 9,
'окт': 10,
'ноя': 11,
'дек': 12,
'сегодня': datenow,
'вчера': dateyesterday
}
def int_value_from_ru_month(date_str):
for k, v in RU_MONTH_VALUES.items():
date_str = date_str.replace(k, str(v))
return date_str
date_str = get_val
date_str = int_value_from_ru_month(date_str)
try:
d = datetime.strptime(date_str, '%d %m, %H:%M')
except:
d = datetime.strptime(date_str, '%d.%m.%Y, %H:%M')
if (d.year == 1900):
if(d.month - dnstr.month > 1):
d = d.replace(year=dnstr.year - 1)
else:
d = d.replace(year=dnstr.year)
d = d.replace(day=pastdate)
return d.strftime('%d.%m.%Y, %H:%M')
def rowIndex(id,date):
if id <= 2000:
return time_converter(date, 3)
if 2000 < id <= 14000:
return time_converter(date, 4)
if 14000 < id <= 26000:
return time_converter(date, 5)
if 26000 < id <= 39500:
return time_converter(date, 6)
if 39500 < id <= 50000:
return time_converter(date, 7)
return date
df['publicDate'] = df.apply(lambda x: rowIndex(x['index'],x['publicDate']),1)
df.sort_values(by='index', ascending=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment