Saravanan666/pypi-org huggingface dataset:
Package: bsif.bashDist
ContentsOverviewSupportDocumentationInstallationUsageOverviewBSIF-bashDist: A wrapper for packaging of BSIF bash files for insertion
into BISOS.SupportFor support, criticism, comments and questions; please contact the
author/maintainerMohsen Bananat:http://mohsen.1.banan.byname.net/contactDocumentationPart of ByStar Digital Ecosystemhttp://www.by-star.net.This module’s primary documentation is inhttp://www.by-star.net/PLPC/180047Installationsudo pip install bsif.bashDistUsage/usr/local/bin/bx-bases-bash.py
Package: bsimport
bsimportA Python tool for importing Markdown files to aBookstackinstance.Important noticeThis project is no longer maintained. I don't use Bookstack anymore so I'm not
sure if it still works: if you have any feedback, please share it by opening an
issue.MotivationI currently useObsidianfor all my note-taking needs.
I wanted to test Bookstack with my existing notes, and since it has an API, I
created this tool to import them.I usedTyperto create the CLI, and implemented
my own incomplete wrapper of the API.FeaturesImport a single file or an entire directory:A single file is imported as a page, so it will ask for the ID of the book
you want to add the page to. You can list your accessible books withpython -m bsimport list-books.A directory is imported as a book: any Markdown files found directly
inside will be imported as pages of this book.If a subdirectory is found, it will be imported as a chapter, and any
Markdown files inside it will be imported as pages of that chapter.If a subdirectory of a subdirectory is found, it will be completely
ignored, even if it contains Markdown files.Support for tags: Obsidian uses aYAML front
matterto add
tags and other information at the top of the page. Currently, only tags
created with the formattags: [tag1, tag2, tag3]are supported.  This means
the following YAML list formatis notsupported:tags:-tag1-tag2-tag3Additionally, any other front matter key such asaliaseswill be ignored.The API token and Bookstack URL are saved in a configuration file. You can get
the path to the file withpython -m bsimport where.UsageGet the API token:Login to your Bookstack instance.Edit your profile.At the bottom of the page, create a new token.
Save both the ID and the secret.Install the package with:python3-mpipinstallbsimportRun theinitcommand:python-mbsimportinitIt will ask you for the token ID and secret, as well as the URL to your
Bookstack.Then import your files with:python-mbsimportimport/path/to/fileTo modify the codeDownload or clone the code.(Optional but recommended) Create a virtual environment: seehttps://docs.python.org/3/library/venv.html.
Example:python3-mvenv.venvInstall the dependencies:python-mpipinstall-rrequirements.txt-rdev-requirements.txt
Package: bsimx
bsimxThe agent-based modeling tool withdeck.gl,networkxandosmnx..InstallationpipinstallnetworkxosmnxbsimxGetting Startedimportosmnxasoxfrombsimximportpreview,Agent,simulateG=ox.graph_from_place("Takamatsu Hayashi",network_type="drive")classEscaper(Agent):start:intdefon_started(self):self.set_start_node(self.start)self.set_goal_node(1042117440)self.set_speed(1.0)sr=simulate([Escaper(start=1042116599),Escaper(start=4111619945)],G)preview(sr)
Package: bsite
一、简介bsite是用于采集B站用户视频列表页、视频评论数据的python包。二、安装pip install bsite三、使用方法3.1 初始化Bsite类需要先登录B站，使用开发者工具获取自己浏览器上的的cookies。获取方法可以参考京东评论实战视频frombsiteimportBsitecookies={"cookie":"登录B站后的cookies"}bs=Bsite(cookies=cookies)3.2 bvid与aid转换B站的视频链接https://www.bilibili.com/video/BV1AE411r7ph其中BV1AE411r7ph是该视频的bvid号， 但在B站后台有一个与bvid对应的id号-aidbvid与aid可以互相转化，Bsite内置了两个转化方法Bsite.aid2bvid(aid)Bsite.bvid2aid(bvid)例如将BV1AE411r7ph转为aidbs.bvid2aid(bvid="BV1AE411r7ph")72010301同理将 72010301 转为 bvidbs.aid2bvid(aid=72010301)BV1AE411r7ph3.3 下载某用户所有视频信息Bsite.video_list(mid, csvfpath)获取用户的所有已上传的视频信息。mid 用户的id，例如我的B站视频主页https://space.bilibili.com/122592901其中122592901就是midcsvfpath csv文件路径，用于存储视频信息。注意：为了保证所有数据均能正常存储不出错，强制使用utf-8编码，微软office打开该csv会乱码，可以用记事本或者WPS打开一般在B站查看某用户【投稿】栏，可以看到ta的所有上传视频。Bsite可以帮我们得到的信息有title、subtitle、author 标题、副标题、作者aid、bvid 视频链接的id号mid 用户的id。例如我的B站视频主页https://space.bilibili.com/122592901其中122592901就是midcreated 上传时间description 视频简介pic 视频首图play 播放次数length 视频时长获取DJI大疆创新https://space.bilibili.com/232472043/video所有投稿视频相关信息。bs.video_list(mid=232472043,csvfpath='dji_videos.csv')3.4 获取某视频内的所有评论Bsite.comments(aid, csvfpath)aid  B站视频的id号，如果只有bvid没有aid，可以先使用内置的方法把bvid转为aidcsvfpath csv文件路径，用于存储评论数据。注意：为了保证所有数据均能正常存储不出错，强制使用utf-8编码，微软office打开该csv会乱码，可以用记事本或者WPS打开采集到的评论数据包括content  评论内容device 评论者使用的设备like 点赞数rcount 该评论追评和互动数ctime 评论创建时间avatar 评论者头像level 评论者等级sex 评论者性别sign 评论者签名uname 评论者昵称mid 评论者的iddiag 该评论是原始评论，还是某评论的互动获取该视频https://www.bilibili.com/video/BV1E54y1C7MF所有的评论aid=bs.bvid2aid('BV1E54y1C7MF')bs.comments(aid=aid,csvfpath='comments.csv')如果如果您是经管人文社科专业背景，编程小白，面临海量文本数据采集和处理分析艰巨任务，个人建议学习《python网络爬虫与文本数据分析》视频课。作为文科生，一样也是从两眼一抹黑开始，这门课程是用五年时间凝缩出来的。自认为讲的很通俗易懂o(￣︶￣)o，python入门网络爬虫数据读取文本分析入门机器学习与文本分析文本分析在经管研究中的应用感兴趣的童鞋不妨 戳一下《python网络爬虫与文本数据分析》进来看看~更多B站:大邓和他的python公众号：大邓和他的python知乎专栏：数据科学家
Package: bskillskit
It is a helper tool with reference to box skills. It is not official.This module refers to the box skill kit nodejs and the Box Python SDK.https://github.com/box/box-skills-kit-nodejshttps://github.com/box/box-python-sdkInstall```shpip install bskillskit```Example```pythonfrom bskillskit import FileReaderfrom bskillskit import SkillsWriterfrom bskillskit import SkillsErrorEnum# Interpret the event from Boxjson_req = { ... }file_reader = FileReader(json_req)skills_writer = SkillsWriter(json_req)# Save a status update back to Boxskills_writer.saveProcessingCard()# Download file from Boxwith open(filereader.file_name, 'wb') as f:file_reader.download_to(f)# Execute iference processingresult_is_not_error = Trueif result_is_not_error:# Write metadata back to Boxtopi_card_json = skills_writer.create_topics_card([{ 'text': 'Hello' },{ 'text': 'File' }])transcripts_card_json = skills_writer.create_transcripts_card([{'text': 'Hello file','appears': [{'start': 0,'end': 1}]}],1)face_card_json = skills_writer.create_faces_card([{'text': "if image doesn't load this text is shown",'image_url': 'https://seeklogo.com/images/B/box-logo-646A3D8C91-seeklogo.com.png'}],None,'Logos')skills_writer.save_data_cards([topi_card_json, transcripts_card_json, face_card_json])else:# Using error cards to display errorsskills_writer.save_error_card(SkillsErrorEnum.INVALID_FILE_FORMAT)```
Package: bsky
bsky: Simple, idiomatic client library for atproto.com ("Bluesky")Status:it doesn't really work yet and will eat your dataThis is a project to implement components of the proposed Bluesky AT
Protocol (atproto.com) for federated social media.HOWTO: Release pypi.org PackageGo totest.pypi.org(and then laterpypi.org) and generate an API token for
your account (assumign you already have an account).Install deps (on Debian/Ubuntu):sudo apt install python3-build python3-twineBuild this package:python3 -m buildRun the upload. When propted, use__token__for username, and the API token
as password.# for test.pypi.org
python3 -m twine upload --repository testpypi dist/*

# for regular pypi.org
python3 -m twine upload dist/*
Package: bsky-bridge
bsky-bridge: A Python Library for the BlueSky APIbsky-bridgeis a Python library designed to bridge the interaction between Python applications and the BlueSky Social Network via its API.Table of ContentsFeaturesInstallationUsageCreating a SessionPosting ContentPosting ImagesContributionLicenseFeaturesEasy authentication with the BlueSky API.Functions to post text and images to BlueSky via the API.Installationpipinstallbsky-bridgeUsageCreating a SessionStart by establishing a session with your BlueSky handle andApp passwords:frombsky_bridgeimportBskySessionsession=BskySession("your_handle.bsky.social","your_password")Posting ContentAfter initializing a session, you can post text to BlueSky:frombsky_bridgeimportpost_textresponse=post_text(session,"Hello BlueSky!")print(response)Posting ImagesTo post images along with text, you can use thepost_imagemethod:frombsky_bridgeimportpost_imagepostText="Check out this cool image!"imagePath="path_to_your_image.jpeg"altText="An awesome image"response=post_image(session,postText,imagePath,altText)print(response)Note: The library automatically handles resizing and compressing larger images to ensure they do not exceed 1 MB in size, all while maintaining a quality balance. This ensures efficient and quick image uploads.ContributionContributions are welcome! Please submit issues for any bug or problem you discover, and pull requests for new features or fixes.LicenseMIT License
Package: bsl
BrainStreamingLayer(Documentation website)provides a real-time brain signal streaming framework.BSLcontains an improved python-binding for the Lab Streaming Layer C++ library,bsl.lsl, replacingpylsl. This low-level binding is used in high-level objects to
interact with LSL streams.Any signal acquisition system supported by native LSL or OpenVibe is also
supported by BSL. Since the data communication is based on TCP, signals can be
transmitted wirelessly. For more information about LSL, please visit theLSL github.InstallBSL supportspython ≥ 3.8and is available onPyPI.
Install instruction can be found on thedocumentation website.AcknowledgmentBSLis based onNeuroDecode. The original version developed byKyuhwa Leewas recognised atMicrosoft Brain Signal Decoding competitionwith the First Prize Award (2016) after achieving high decoding accuracy.BSLis based on the refactor version byArnaud Desvachezfor theFondation Campus Biotech Geneva (FCBG)and
development is still supported by theHuman Neuroscience Platform (FCBG).Copyright and licenseThe code is released under theMIT License.
Package: bsl2sq
Поисковик bsl модулей для sonarqubeПоиск bsl файлов проекта (конфигурации 1С) по вхождению в подсистемы.ВозможностиРабота в ОС семейства: Linux, Windows, Mac OS X;Вывод полного или относительного пути к файлам с расширением .bsl;Вывод списка путей в файл sonar-project.properties или в поток стандартного вывода;Вывод кириллических символов в символах UNICODE.Установка и обновлениеУстановить Python версии не ниже 3.6;Установить пакет bsl2sq из PyPI командой:pipinstallbsl2sqДля обновления пакета необходимо воспользоваться командой:pipinstall-Ubsl2sqАнализ файлов выгрузки выполняется для платформы 1С версии не ниже 8.3.10.Использование модуляbsl2sq [-h] [-f FILE] [-a] [-u] [-v] [-V] sourcedirectory parseprefix- структура вызова скриптаОбязательные аргументы:sourcedirectory- путь к корневой папке с выгруженной конфигурацией 1с;parseprefix-  префиксы подсистем, в которых будет осуществляться поиск путей до файлов объектов метаданных. Разделителем префиксов является пробел, к примерурн_ пк_ зс_Опциональные параметры:-h, --help- вызов справки;-f FILE, --file FILE- полный путь к файлу sonar-project.properties, в который будет выполняться выгрузка путей объектов метаданных на место переменной$inclusions_line;-a, --absolute- в случае указания флага будут выгружаться полные пути к файлам. Без флага только относительные пути;-u, --unicode- в случае указания флага будут выгружаться все кириллические символы в символах unicode;-v, --verbose- в случае указания флага будут выводиться подробная информация;-V, --version- вывод версии скрипта.Пример файлаsonar-project.propertiesдля первоначального запуска:# Фильтры на включение в анализ. В примере ниже - только bsl и os файлы.sonar.inclusions=$inclusions_lineПри последующих запусках скрипт автоматически будет удалять предыдущий список  объектов и заполнять новыми в файлеsonar-project.properties. Замена будет выполняться между двумя ключевыми словамиsonar.inclusions=и$inclusions_endПример использования скрипта в Linuxbsl2sq"/Users/gostmair/GitReps/rn_erp/src/conf""рн_"-u-f"/Users/gostmair/GitReps/rn_erp/sonar-project.properties"Пример использования скрипта в Windowsbsl2sq c:\PythonScripts\rn_erp\src\conf\ рн_ -u -f d:\rn_erp\sonar-project.properties
Package: bslib
bslib - battery storage libraryRepository with code tobuild adatabasewith relevant data from PerMod database (HTW Berlin) and "Stromspeicher-Inspektion"simulateac- and dc-coupled battery storages with regards to electrical power (ac and dc) and state-of-charge as timeseries.For the simulation, it is possible to calculate outputs of aspecific manufacturer + modelor alternatively for one of2 different generic battery storage types.For reference purposes:DOI:https://doi.org/10.5281/zenodo.6514527Citation: Kai Rösken, Tjarko Tjaden, & Hauke Hoops. (2022). FZJ-IEK3-VSA/bslib: v0.7. Zenodo.https://doi.org/10.5281/zenodo.6514527DocumentationThe documentation is still under development.UsageSimply install viapip install bslibor clone repository and create environment via:git clone https://github.com/FZJ-IEK3-VSA/bslib.gitconda env create --name bslib --file requirements.txtAfterwards you're able to create some code withimport bsliband use the included functionsload_database,get_parametersandsimulate.Battery models and Group IDsThe bslib_database.csv contains the following number of battery storages, sorted by Group ID[Group ID]: CountDescription[S_ac]: 2AC-coupled[S_dc]: 3DC-coupled[INV]: 2PV InverterDatabaseAll resulting database CSV file are under.The following columns are available for every battery storage of this libraryColumnDescriptionComment......Input-Data and further developmentIf you find errors or are interested in develop the bslib, please create an ISSUE and/or FORK this repository and create a PULL REQUEST.LicenseMIT LicenseCopyright (c) 2022You should have received a copy of the MIT License along with this program.
If not, seehttps://opensource.org/licenses/MITAbout UsWe are theInstitute of Energy and Climate Research - Techno-economic Systems Analysis (IEK-3)belonging to theForschungszentrum Jülich. Our interdisciplinary department's research is focusing on energy-related process and systems analyses. Data searches and system simulations are used to determine energy and mass balances, as well as to evaluate performance, emissions and costs of energy systems. The results are used for performing comparative assessment studies between the various systems. Our current priorities include the development of energy strategies, in accordance with the German Federal Government’s greenhouse gas reduction targets, by designing new infrastructures for sustainable and secure energy supply chains and by conducting cost analysis studies for integrating new technologies into future energy market frameworks.
Package: bsm
Bundled software managerInstallationInstallBSMwithcurlorwgetcurl -sSL https://raw.githubusercontent.com/bsmhep/bsm/master/script/install.sh | sh -s [BSM_DIR]orwget -qO- https://raw.githubusercontent.com/bsmhep/bsm/master/script/install.sh | sh -s [BSM_DIR]IfBSM_DIRis omitted,BSMwill be installed in the
current directory.Install Software with BSMSetupBSM:. <BSM_DIR>/setup.shList available software version:bsm ls-remoteSpecify software version and where to install:bsm [-r <SOFTWARE_ROOT>] install <version>If-r<SOFTWARE_ROOT>is not specified, everything will be
installed in the current directory.Multiple versions could be installed under the same software root
directory.ConfigurationCreate the configuration file if it does not exist:[ -e ~/.bsm.conf ] || bsm config -e > ~/.bsm.confEdit~/.bsm.confand uncommentsoftware_root:software_root: <SOFTWARE_ROOT>Select Software VersionList local installed software version:bsm -r <SOFTWARE_ROOT> lsSelect local software version you would like to use:bsm -r <SOFTWARE_ROOT> use <version>
Package: bsmschema
BIDS Stats Models SchemaThis package contains aPydanticdescription of the
BIDS Stats Models format, which can be used as a schema validator or generate JSON
schema for independent validation.InstallingbsmschemaFrom the Python package indexpip install bsmschemaFrom sourcegit clone https://github.com/bids-standard/stats-models.git
pip install stats-models/bsmschemaYou may wish to install in editable mode, to ensure that your changes get propagated without
reinstalling:pip install -e stats-models/bsmschemaHow to run schema validatorfrombsmschema.modelsimportBIDSStatsModelBIDSStatsModel.parse_file('stats-models/specification/examples/model-example_smdl.json')
Package: bsn
bsnGenerate or validate bsn (burger service nummer, dutch social security number)A bsn (burger service number, dutch social security number) is used in Netherlands to identify a person for governmental organisations. The numbers are subject to an algorithm.Verification algorithmmod(sum(Position_of_digit * digit),11) = 0whereas the first position should be considered as negativeExampleConsider the following number: 319072356(9 x 3) + (8 x 1) + (7 x 9) + (6 x 0) + (5 x 7) + (4 x 2) + (3 x 3) + (2 x 5) + (-1 x 6) = 154
154 mod 11 = 0Initiate the module and create instanceimport bsn
a = bsn.bsn()Validate numbera.validate_bsn(number)Generate n numbersa.generate_bsn(n)
Package: bsn-sdk
BSN Python SDKAuthor: 李大狗LeeduckgoOrg: 上海对外经贸大学·人工智能与变革管理学院·区块链技术与应用研究中心bsn-python-sdk is a Python library for communicating withBlockchain Service Network, It is used for building blockchain Apps with BSN.It provides:5 APIs ( create, update, query, delete, get_history ) abount default chainCode in BSN.bsn-python-sdk 是一个用于和 BSN 区块链服务网络相联系的 Python 库，其被用于构建和 BSN 相关的 区块链 App。它目前提供：包含「增、减、查、改、查询历史记录」的默认链码包中的五个接口的调用。InstallingInstall and update usingpip:pip3 install bsn-sdkA Simple Examplefrombsn_sdkimportOperator# user_code, app_code, chain_code, url and cert_pathop=Operator("reddate","CL1851016378620191011150518","cc_base","https://quanzhounode.bsngate.com:17602/api/node/reqChainCode","./certificate")# save_datares=op.save_data("leeduckgo5","test")# res = {'success': True, 'payload': {'txId': 'c69af29cc00c68456b9e6fe9013f8e4f15ed6e09e3b2250ae3561b9a122ec509', 'context': None}}# get_datares=op.get_data("leeduckgo5")# {'success': True, 'payload': {'txId': '92b61460a31d323d54121c25fced24cacc5102b309f310044ad6b36f42bf05a6', 'context': 'test'}}# update_datares=op.update_data("leeduckgo5","testtest")# {'success': True, 'payload': {'txId': 'abfe9ee4628efc07086fb81a5b37ef5126898f042868c3d9fade7a7d316ec613', 'context': 'SUCCESS'}}# delete_datares=op.delete_data("leeduckgo5")# {'success': True, 'payload': {'txId': '1b0f298004c9a617ed84dfd4bb989ed03f46e6676668cccfb3bd23117fcd6356', 'context': 'SUCCESS'}}# get_historyres=op.get_history("leeduckgo5"){'success':True,'payload':{'txId':'3ec3174424070b04311af22e0694bba6e099821090cb761a7fae60ce89ef29d4','context':[{'txId':'c69af29cc00c68456b9e6fe9013f8e4f15ed6e09e3b2250ae3561b9a122ec509','dataInfo':'{"BaseKey":"leeduckgo5","BaseInfo":"test"}','txTime':'2020-01-22 13:18:37','isDelete':False},{'txId':'abfe9ee4628efc07086fb81a5b37ef5126898f042868c3d9fade7a7d316ec613','dataInfo':'{"BaseKey":"leeduckgo5","BaseInfo":"testtest"}','txTime':'2020-01-22 13:20:03','isDelete':False},{'txId':'1b0f298004c9a617ed84dfd4bb989ed03f46e6676668cccfb3bd23117fcd6356','dataInfo':'','txTime':'2020-01-22 13:22:21','isDelete':True}]}}PlanIt will supported more chainCode next( ´Д｀)y━・.
Package: bson-extra
bson_extraA package that provides timezone support and custom type handling functionality for MongoDB bson ->https://api.mongodb.com/python/current/api/bson/index.htmlMongoDB bson is great - but it doesn't allow for certain custom types - specifically timezone support.  This package rectifies that.This package provides a newdumpsandloadsmethod that overrides the~bson.json_util.dumpsand~bson.json_util.loadfunctions
in a few key places to support timezones - everything else works in the same way as in the core package.Hooks are also provided so that you can handle custom type handling as necessary.Installationpip install bson_extraUsagebson_extrahandle timezone aware and timezone naive datetimes.bson_extraretains all existing functionality of~bson.json_util.dumps- meaning you can providejson_optionsto configure the output
as required.  Hooks are also provided so that you can implement your own custom handling as required.Dumping a timezone aware datetime>>>fromdatetimeimportdatetime>>>frombson_extraimportbson_extra>>>importpytz>>>timezone=pytz.timezone("America/New_York")>>>dt=datetime(2020,6,20,12,30,45).astimezone(timezone)>>>bson_extra.dumps(dt)'{"$date": 1592652645000, "$zone": "America/New_York", "$offset": {"total_seconds": -14400.0}}'Loading a timezone aware datetime>>>fromdatetimeimportdatetime>>>frombson_extraimportbson_extra>>>dumped_data='{"$date": 1592652645000, "$zone": "America/New_York", "$offset": {"total_seconds": -14400.0}}'>>>bson_extra.loads(dumped_data)datetime(2020,6,20,7,30,45,tzinfo=<DstTzInfo'America/New_York'EDT-1day,20:00:00DST>)Dumping a timezone naive datetime>>>fromdatetimeimportdatetime>>>frombson_extraimportbson_extra>>>dt=datetime(2020,6,20,12,30,45)>>>bson_extra.dumps(dt)'{"$date": 1592656245000, "$zone": null, "$offset": null}'Loading a timezone naive datetime>>>fromdatetimeimportdatetime>>>frombson_extraimportbson_extra>>>dumped_data='{"$date": 1592656245000, "$zone": null, "$offset": null}'>>>bson_extra.loads(dumped_data)datetime(2020,6,20,7,30,45)Handling custom typesWhat if you want to handle a specific type that isn't currently supported bybson?bson_extrasupplies some hooks to enable you to do this easily by subclassingBsonExtra>>>frombson_extraimportBsonExtra>>>classCustomBsonExtra(BsonExtra):>>>defdump_object_hook(self,obj,json_options):>>>ifisinstance(obj,int):>>># By default `bson`  dumps integers as a string>>>result={"$integer":obj}>>>else:>>>result=super(CustomBsonExtra,self).dump_object_hook(obj,json_options)>>>returnresult>>>>>>defload_object_hook(self,dct,*args,**kwargs):>>>result=super(CustomBsonExtra,self).load_object_hook(dct,*args,**kwargs)>>>if"$integer"indct:>>>returnint(dct['$integer'])>>>returnresult>>>>>># By default `bson` dumps integers as strings>>>bson_extra=CustomBsonExtra()>>>bson_extra.dumps(1)>>>'{"$integer": 1}'>>>>>>bson_extra.loads('{"$integer": 1}')>>>1Running the testspython setup.py test
Package: bsonschema
bsonschemaSimple bson validator written similarly tojsonschemabut for BSON types.Example of Useimport bsonschema;

inst = read_bson_from_disk("./tests/test_bson_for_validation.bson")
valid = bsonschema.Validator(json.load(open("./tests/mdb_schema.json", "r")))
valid.validate(inst)
print('Test file passed validation.')
Package: bson-timezone
bson_timezoneA package that provides timezone support for MongoDB bson ->https://api.mongodb.com/python/current/api/bson/index.htmlMongoDB bson is great - but it doens't allow for timezone support.  This package rectifies that.This package provides a newdumpsandloadsmethod that overrides the~bson.json_util.dumpsand~bson.json_util.loadfunctions
in a few key places to support timezones - everything else works in the same way as in the core package.Installationpip install bson_timezoneUsagebson_timezonehandle timezone aware and timezone naive datetimes.bson_timezoneretains all existing functionality of~bson.json_util.dumps- meaning you can providejson_optionsto configure the output
as required.Dumping a timezone aware datetime>>>fromdatetimeimportdatetime>>>frombson_timezoneimportbson_tz_dumps>>>importpytz>>>timezone=pytz.timezone("America/New_York")>>>dt=datetime(2020,6,20,12,30,45).astimezone(timezone)>>>bson_tz_dumps(dt)'{"$date": 1592652645000, "$zone": "America/New_York", "$offset": {"total_seconds": -14400.0}}'Loading a timezone aware datetime>>>fromdatetimeimportdatetime>>>frombson_timezoneimportbson_tz_loads>>>dumped_data='{"$date": 1592652645000, "$zone": "America/New_York", "$offset": {"total_seconds": -14400.0}}'>>>bson_tz_loads(dumped_data)datetime.datetime(2020,6,20,7,30,45,tzinfo=<DstTzInfo'America/New_York'EDT-1day,20:00:00DST>)Dumping a timezone naive datetime>>>fromdatetimeimportdatetime>>>frombson_timezoneimportbson_tz_dumps>>>dt=datetime(2020,6,20,12,30,45)>>>bson_tz_dumps(dt)'{"$date": 1592656245000, "$zone": null, "$offset": null}'Loading a timezone naive datetime>>>fromdatetimeimportdatetime>>>frombson_timezoneimportbson_tz_loads>>>dumped_data='{"$date": 1592656245000, "$zone": null, "$offset": null}'>>>bson_tz_loads(dumped_data)datetime.datetime(2020,6,20,7,30,45)Running the testspython setup.py test