python-%、~含义解释

1.%有哪几种含义?

查找手册

翻看《The Python Libary Reference》python库指南中附录index部分(P1899):

% (percent):
datetime format, 198, 594, 596
environment variables expansion (Windows), 377, 1798
interpolation in configuration files, 493
operator, 31
printf-style formatting, 51, 65

根据index中用法索引逐项来看:

  • datetime format:表示日期格式
  • environment variables expansion 环境变量扩展
  • interpolation in configureation files 插入设置文件
  • operator:取余
  • printf-style formatting:输出格式化

环境变量扩展:

Expands environment variable placeholders %NAME% in strings like REG_EXPAND_SZ:
    ExpandEnvironmentStrings('%windir%')
    'C:\\Windows'

插入设置文件

home_dir: /Users
my_dir: %(home_dir)s/lumberjack
my_pictures: %(my_dir)s/Pictures

实例:

cls_info = ['%s\n(%d %s)'% (estimator_conf['name'],
                            estimator_conf['complexity_computer'](estimator_conf['instance']),
                            estimator_conf['complexity_label']) 
                            for estimator_conf in configuration['estimators']]

2.~含义是什么?

查手册:

  • ~ (tilde)
    home directory expansion, 377
    operator, 32

除了表示家目录外,表示操作符按位取反(the bits of inverted)
~5=-6
~-11=10
可以理解为取0为第一个正数,取坐标轴对称点。
解析见:https://blog.youkuaiyun.com/oAlevel/article/details/79267644

### Python 中 `time.strftime` 函数的含义和用法 #### 背景介绍 `time.strftime` 是 Python 标准库 `time` 模块中的一个重要函数,用于将时间元组(通常是通过 `time.localtime()` 或 `time.gmtime()` 获取的时间对象)转换为格式化的字符串表示形式。它的行为类似于 C 语言中的 `strftime` 函数,允许开发者按照特定的模板格式化日期和时间[^1]。 #### 基本语法 ```python time.strftime(format[, t]) ``` - **format**: 字符串,指定输出的时间/日期格式。 - **t** *(可选)*: 时间元组或结构体(如由 `time.localtime()` 返回的对象)。如果省略,则默认使用当前本地时间。 #### 常见格式化指令 以下是常用的 `%` 开头的格式化命令及其对应的解释[^2]: | 指令 | 描述 | |------|------| | `%Y` | 年份,四位数表示(如:2023) | | `%m` | 月份,两位数表示(01 到 12) | | `%d` | 日,两位数表示(01 到 31) | | `%H` | 小时(24小时制),两位数表示(00 至 23) | | `%I` | 小时(12小时制),两位数表示(01 至 12) | | `%M` | 分钟,两位数表示(00 至 59) | | `%S` | 秒,两位数表示(00 至 61;考虑闰秒情况) | | `%f` | 微妙部分(注意此选项仅适用于 `datetime.datetime.strftime`) | #### 使用示例 以下是一些具体的例子展示如何应用 `time.strftime` 来生成不同风格的时间戳: ##### 示例 1: 输出标准 ISO8601 格式的日期时间 ```python import time formatted_time = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) print(formatted_time) # e.g., "2023-03-17T14:45:00Z" ``` ##### 示例 2: 自定义日历显示样式 ```python custom_date_string = time.strftime("Today is %A, the %d of %B.", time.localtime()) print(custom_date_string) # e.g., "Today is Friday, the 17 of March." ``` ##### 示例 3: 结合其他字符串拼接复杂表达式 ```python log_message = f"Process started at {time.strftime('%X')}" print(log_message) # e.g., "Process started at 14:45:00" ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值