Fundamentals 7 min read

Useful Python Code Snippets for Time, Data Formatting, JSON Fixing, URL Query Parsing, File Comments, INI Config, and Path Management

This article presents a collection of practical Python code snippets covering timestamp retrieval, date formatting, JSON correction, URL query parsing, file comment extraction, INI configuration reading, and project‑relative path resolution to help developers handle common tasks efficiently.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Useful Python Code Snippets for Time, Data Formatting, JSON Fixing, URL Query Parsing, File Comments, INI Config, and Path Management

This article provides a set of ready‑to‑use Python utilities for everyday programming challenges.

1. Second‑level and millisecond‑level timestamp retrieval

# 获取当前秒级时间戳
def millisecond(add=0):
    return int(time.time()) + add
# 获取当前毫秒级时间戳
def millisecond_new():
    t = time.time()
    return int(round(t * 1000))

The two functions return the current time as a Unix timestamp in seconds or milliseconds; the first accepts an optional offset.

2. Current date string retrieval

def getNowTime(tianshu=0):
    shijian = int(time.strftime('%Y%m%d')) - tianshu
    print(shijian)
    return shijian

This function returns the current date in YYYYMMDD format and can subtract a given number of days.

3. Fixing JSON data without quotes

def json_json():
    with open("源文件地址", "r") as f, open("目标文件地址", "a+") as a:
        a.write("{")
        for line in f.readlines():
            if "[" in line.strip() or "{" in line.strip():
                formatted_line = "'" + line.strip().replace(":", "':").replace(" ", "") + ","
                print(formatted_line)  # 输出修复后的行
                a.write(formatted_line + "\n")
            else:
                formatted_line = "'" + line.strip().replace(":", "':'").replace(" ", "") + "',"
                print(formatted_line)  # 输出修复后的行
                a.write(formatted_line + "\n")
        a.write("}")

The function reads a raw JSON‑like file, adds missing quotes around keys and values, and writes a corrected JSON file.

4. Converting URL query strings to JSON (dictionary)

from urllib.parse import urlsplit, parse_qs

def query_json(url):
    query = urlsplit(url).query
    params = dict(parse_qs(query))
    cleaned_params = {k: v[0] for k, v in params.items()}
    return cleaned_params

This utility parses the query part of a URL and returns a dictionary with single values for each parameter.

5. Extracting first‑line comments from Python files

import os

def get_first_line_comments(directory, output_file):
    python_files = sorted([f for f in os.listdir(directory) if f.endswith('.py') and f != '__init__.py'])
    comments_and_files = []
    for file in python_files:
        filepath = os.path.join(directory, file)
        with open(filepath, 'r', encoding='utf-8') as f:
            first_line = f.readline().strip()
            if first_line.startswith('#'):
                comment = first_line[1:].strip()
                comments_and_files.append((file, comment))
    with open(output_file, 'w', encoding='utf-8') as out:
        for filename, comment in comments_and_files:
            out.write(f"{filename}: {comment}\n")
# 示例用法
get_first_line_comments('指定文件夹', '指定生成文件路径.txt')

The function scans a directory for .py files, captures the leading comment line, and writes a mapping of filenames to comments.

6. Reading INI configuration files

import sys
import os
import configparser

class ReadConfig:
    def __init__(self, config_path):
        self.path = config_path
    def read_sqlConfig(self, fileName="sql.ini"):
        read_mysqlExecuteCon = configparser.ConfigParser()
        read_mysqlExecuteCon.read(os.path.join(self.path, fileName), encoding="utf-8")
        return read_mysqlExecuteCon._sections
    def read_hostsConfig(self, fileName="hosts.ini"):
        read_hostsCon = configparser.ConfigParser()
        read_hostsCon.read(os.path.join(self.path, fileName), encoding="utf-8")
        return read_hostsCon._sections
# 示例用法
config_reader = ReadConfig('配置文件所在路径')
sql_config = config_reader.read_sqlConfig()
hosts_config = config_reader.read_hostsConfig()["hosts"]

The ReadConfig class abstracts reading of sql.ini and hosts.ini files, returning their sections as dictionaries.

7. Setting a global file path relative to the project root

import os

def setFilePath(filePath):
    current_module_path = os.path.dirname(os.path.abspath(__file__))
    project_root_path = os.path.dirname(os.path.dirname(current_module_path))
    path = os.path.join(project_root_path, filePath.lstrip('/'))
    return os.path.abspath(path)
# 示例用法
confPath = setFilePath("地址文件路径")

This helper computes an absolute path for a resource located under the project’s root directory, simplifying resource management.

JSONDateTimefile managementutilitiesconfig
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.