Documentation
Functions
cookies_utilities.copy_datetime
- cookies_utilities.copy_datetime(dt, options={})
Create a copy of a datetime.datetime object.
- Parameters:
dt (datetime.datetime) – The original object.
options (dict) – If you wish to overwrite certain fields, please specify them using this dictionary (optional). The keys must be in [‘year’, ‘month’, ‘day’, ‘hour’, ‘minute’, ‘second’, ‘microsecond’, ‘tzinfo’, ‘fold’].
- Return type:
datetime.datetime
Example
import cookies_utilities as cu
import datetime
dt = datetime.datetime.strptime('2016-07-01 02:15:00', '%Y-%m-%d %H:%M:%S')
dt_copy = cu.copy_datetime(dt, {'minute': 0}) # --> 2016-07-01 02:00:00
cookies_utilities.get_dates
- cookies_utilities.get_dates(start='2016-07-01 02:00:00', end='2016-07-02 01:00:00', format='%Y-%m-%d %H:%M:%S', delta={'days': 0, 'hours': 1, 'minutes': 0, 'weeks': 0}, geniter=False, cast_str=True, format_out=None)
Returns a list of times from the ‘start’ time to the ‘end’ time, incremented by ‘delta’. Please ensure ‘delta’ is greater than or equal to 1 microsecond.
If you’re using the result as an iterator, it is recommended to set geniter=True.
- Parameters:
start (string) – Start time string.
end (string) – End time string (inclusive).
format (string) – Conversion format for datetime.strptime.
delta (dict) – Timedelta as args for datetime.timedelta (>= 1 microsecond).
geniter (bool) – Whether to return as a generator iterator (default False).
cast_str (bool) – Whether to convert output to string (default True).
format_out (string) – Conversion format for output (default same to format).
- Return type:
list (or generator iterator) of string (or datetime.datetime)
Example
An example of incrementing by one day.
import cookies_utilities as cu
dates = cu.get_dates(
start='2016/07/01', end='2016/07/03', format='%Y/%m/%d',
delta={'days': 1}, format_out='%Y-%m-%d')
print(dates)
['2016-07-01', '2016-07-02', '2016-07-03']
An example of incrementing by 20 minutes.
import cookies_utilities as cu
dates = cu.get_dates(
start='2016-07-01 02:00:00', end='2016-07-01 03:00:00',
format='%Y-%m-%d %H:%M:%S',
delta={'minutes': 20})
print(dates)
['2016-07-01 02:00:00', '2016-07-01 02:20:00', '2016-07-01 02:40:00', '2016-07-01 03:00:00']
An example of retrieving as a generator iterator.
import cookies_utilities as cu
dates = cu.get_dates(
start='2016/07/01', end='2016/07/03', format='%Y/%m/%d',
delta={'days': 1}, geniter=True)
print(type(dates))
for date in dates:
print(date)
<class 'generator'>
2016/07/01
2016/07/02
2016/07/03
cookies_utilities.convert_time_to_feature
- cookies_utilities.convert_time_to_feature(dt, format='%Y-%m-%d %H:%M:%S', period='day', ceiling=None)
Convert a time to a feature value between 0 and 1. The return feature value represents how much of a period has passed.
For example, if the period is 1 day, a feature value of noon is 0.5.
Note 1: When setting the period to a month, the cycle is considered as 31 days regardless of the actual number of days in that month. This is to ensure that the feature value for ‘the 5th day of any month’ is consistent.
Note 2: When setting the period to a year, the cycle is considered as 366 days regardless of the actual number of days in that year. This is done to ensure that the feature value for ‘the 5th day of any year’ remains the same, regardless of the specific year.
- Parameters:
dt (string) – A time string.
format (string) – Conversion format for datetime.strptime. If you set this argument to None, we expect ‘dt’ to originally be datetime.datetime object.
period (string) – A time period to convert a time to a feature value. This must be in [‘year’, ‘month’, ‘week’, ‘day’, ‘hour’, ‘minute’, ‘second’].
ceiling (string) – If you want to round the time when calculating the feature value, specify the rounding granularity in this argument (optional). This must be in [‘year’, ‘month’, ‘day’, ‘hour’, ‘minute’, ‘second’].
- Return type:
float
import cookies_utilities as cu
feature_value = cu.convert_time_to_feature(
dt='2023-01-02 03:40:50', format='%Y-%m-%d %H:%M:%S',
period='day', ceiling='hour')
# --> 0.125 ( 3:00 am is 12.5% of the day )
feature_value = cu.convert_time_to_feature(
dt='2023-01-02 03:40:50', format='%Y-%m-%d %H:%M:%S',
period='year', ceiling='day')
# --> 0.002732 ( 1.0 / 366.0 )
feature_value = cu.convert_time_to_feature(
dt='2023-01-02 03:40:50', format='%Y-%m-%d %H:%M:%S',
period='month', ceiling='day')
# --> 0.032258 ( 1.0 / 31.0 )
feature_value = cu.convert_time_to_feature(
dt='2023-01-02 03:40:50', format='%Y-%m-%d %H:%M:%S',
period='week', ceiling='hour')
# --> 0.017857 ( 0.125 / 7.0 )
feature_value = cu.convert_time_to_feature(
dt='2023-01-02 03:40:50', format='%Y-%m-%d %H:%M:%S',
period='hour', ceiling='minute')
# --> 0.666667 ( 40.0 / 60.0 )
feature_value = cu.convert_time_to_feature(
dt='2023-01-02 03:40:50', format='%Y-%m-%d %H:%M:%S',
period='minute')
# --> 0.833333 ( 50.0 / 60.0 )
cookies_utilities.has_diff_local_and_remote
- cookies_utilities.has_diff_local_and_remote(local_dir, remote_url, username=None, password=None, exts='html|css|js', binary_exts='png|jpg|pdf')
Recursively checks whether the local directory is synchronized with the specified URL.
For binary files, only their presence and file size will be checked without verifying the content differences.
- Parameters:
local_dir (str) – The path to the local directory.
remote_url (str) – The URL to be checked against.
username (str | None) – The username for basic authentication. If the URL is protected, please specify (optional).
password (str | None) – The password for basic authentication. If the URL is protected, please specify (optional).
exts (str) – A pipe-separated list of file extensions to be checked. Default is “html|css|js” (optional).
binary_exts (str) – A pipe-separated list of binary file extensions to be checked. Default is “png|jpg|pdf” (optional).
- Return type:
None
Example
An example script of check whether the local directory is synchronized with the specified URL.
import cookies_utilities as cu
import getpass
if __name__ == '__main__':
username = getpass.getpass('Please enter username: ')
password = getpass.getpass('Please enter password: ')
while True:
cu.has_diff_local_and_remote(
local_dir='./hoge/',
remote_url='https://hoge/',
username=username, password=password,
exts='html|css|js|tex|sty',
binary_exts='png|jpg|pdf|pptx|ps|eps',
)
print('----- END -----')
user_input = input('Press Enter to continue or type `q` to quit: ')
if user_input == 'q':
break
Classes
cookies_utilities.Stopwatch
- class cookies_utilities.Stopwatch
Stopwatch for measuring processing time.
- press(key='')
Press the stopwatch.
- Parameters:
key (string) – The idenficator for the time (optional).
- show()
Show lap times.
Example
import cookies_utilities as cu
sw = cu.Stopwatch()
sw.press('train start')
# train
sw.press('train end')
# test
sw.press('test end')
sw.show()
time1 (train start - train end): 2.000s
time2 (train end - test end): 1.000s
total: 3.000s
cookies_utilities.HtmlHelper
- class cookies_utilities.HtmlHelper(title=None)
Class to help with creating an HTML file.
- Parameters:
title (str | None) – The title of the HTML (optional).
- append(s)
- Parameters:
s (str) – String to be appended to the HTML body.
- Return type:
None
- append_heading(level, s)
- Parameters:
level (int) – Integer indicating the heading level.
s (str) – Heading String.
- Return type:
None
- append_markdown(md_path, converter)
Reads the markdown file, converts it to HTML, and appends to the body.
- Parameters:
md_path (str) – Path to the markdown file.
converter (Callable[[str], str]) – Function used to convert markdown to HTML.
- Return type:
None
- to_html(out_path)
- Parameters:
out_path (str) – Output path for the HTML file.
- Return type:
None
Example
Below is an example of converting a Markdown file to an HTML file. The mistletoe package is used for the Markdown conversion.
from cookies_utilities import HtmlHelper
import mistletoe
import re
def main(md_path):
hh = HtmlHelper()
# Reads the markdown file, converts it to HTML, and appends to the body.
assert re.search(r'\.md$', md_path)
hh.append_markdown(md_path, mistletoe.markdown)
# You can also customize the CSS.
# Since `css` attribute is a subclass of a dictionary,
# you can set it directly by specifying a key.
# Ex. hh.css['body']['background'] = 'lemonchiffon'
# Using the method below, it checks for the existence of
# the 'body' key and adds it if not present.
hh.css.set('body', 'background', 'lemonchiffon')
hh.to_html(re.sub(r'\.md$', '.html', md_path))
if __name__ == '__main__':
main('./README.md')
Below is an example of outputting a Pandas DataFrame to an HTML file.
from cookies_utilities import HtmlHelper
import pandas as pd
df = pd.DataFrame(columns=['id', 'name'])
df.loc[0] = ['001', 'Alice']
df.loc[1] = ['002', 'Bob']
df.loc[2] = ['003', 'Carol']
hh = HtmlHelper()
hh.append_heading(1, 'Employees')
hh.append(df.to_html(index=False))
hh.to_html('employees.html')