1、安装
brew install python
2、配置 环境变量
·打开
sudo vi ~/.bash_profile
·添加
export PATH="/opt/homebrew/bin:$PATH"
·重载
source ~/.bash_profile
✗ source ~/.zshrc # 按需
3、验证
·方式 1
ls -l /opt/homebrew/bin/python3
·方式 2
echo $PATH
· 方式 3
/opt/homebrew/bin/python3 --version
4、shell 运行 python
- 方法 1
#!/bin/bash
# 定义函数
process_timestamp() {
timestamp=$1
formatted_date=$(python3 -c "from datetime import datetime; print(datetime.fromtimestamp($timestamp).strftime('%Y-%m-%d %H'))")
id=$(python3 -c "from datetime import datetime; print(datetime.fromtimestamp($timestamp).strftime('%Y%m%d%H'))")
echo "timestamp: $timestamp"
echo "id: $id"
echo "Formatted Date: $formatted_date"
}
# 获取当前时间,格式为 yyyy-MM-dd HH:mm:ss
current_time=$(date +"%Y-%m-%d %H:%M:%S")
echo "当前时间:$current_time"
begin_timestamp=$(python3 -c "from datetime import datetime, timezone; print(int(datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0). timestamp()))")
begin_local_time=$(python3 -c "from datetime import datetime; print(datetime.fromtimestamp($begin_timestamp).strftime('%Y-%m-%d %H'))")
echo "begin_timestamp: $begin_timestamp"
echo "begin_local_time: $begin_local_time"
for ((i=0; i<=3; i++)); do
timestamp=$((begin_timestamp - 3600*i))
process_timestamp $timestamp
done
- 方法 2
#!/bin/bash
current_time=$(date +"%Y-%m-%d %H:%M:%S")
echo "当前时间:$current_time"
begin_timestamp=$(python3 -c "from datetime import datetime, timezone; print(int(datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0). timestamp()))")
begin_local_time=$(python3 -c "from datetime import datetime; print(datetime.fromtimestamp($begin_timestamp).strftime('%Y-%m-%d %H'))")
echo "begin_timestamp: $begin_timestamp"
echo "begin_local_time: $begin_local_time"
for ((i=0; i<=3; i++)); do
timestamp=$((begin_timestamp - 3600*i))
formatted_date=$(python3 -c "from datetime import datetime; print(datetime.fromtimestamp(int('$timestamp')).strftime('%Y-%m-%d %H'))")
id=$(python3 -c "from datetime import datetime; print(datetime.fromtimestamp(int('$timestamp')).strftime('%Y%m%d%H'))")
echo "timestamp: $timestamp"
echo "id: $id"
echo "Formatted Date: $formatted_date"
done
结果
当前时间:2024-04-26 19:04:50
begin_hour: 11
begin_utc_time: 2024-04-26 11
begin_timestamp: 1714100400
timestamp: 1714100400
id: 2024042611
Formatted Date: 2024-04-26 11
timestamp: 1714096800
id: 2024042610
Formatted Date: 2024-04-26 10
timestamp: 1714093200
id: 2024042609
Formatted Date: 2024-04-26 09
timestamp: 1714089600
id: 2024042608
Formatted Date: 2024-04-26 08