xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Python script get date and time All In One

Python script get date and time All In One

Python shell script print current datetime to log file

# ✅ 👍 相对路径 env
#!/usr/bin/env bash

# 仅仅适用于 Python ❌
# 指定文件编码 UTF-8
# coding: utf8

# 👎 绝对路径, 存在错误风险
#!/usr/bin/bash

errors

Python !== Shell

$ ./gpio.py 3
  File "/home/pi/Desktop/./gpio.py", line 15
    datetime = $(date '+%Y-%m-%d %T')
               ^
SyntaxError: invalid syntax

image

Solutions

Python get datetime

from datetime import datetime

# 获得当前时间
now = datetime.now()

# 转换为指定的格式
currentTime = now.strftime("%Y-%m-%d %H:%M:%S")

print('currentTime =', currentTime)
# currentTime = 2023-04-12 04:24:24
import datetime

# 获得当前时间
now = datetime.datetime.now()

# 转换为指定的格式
currentTime = now.strftime("%Y-%m-%d %H:%M:%S")

print('currentTime =', currentTime)
# currentTime = 2023-04-12 04:23:40

image

import time

# 获得当前时间戳
now = int(time.time())

#转换为其他日期格式, 如:"%Y-%m-%d %H:%M:%S"
timeArray = time.localtime(now)

currentTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print('currentTime =', currentTime)
# currentTime = 2023-04-12 04:49:44

image

demos

Python script

#!/usr/bin/env python3
# coding: utf8

import RPi.GPIO as GPIO
import time
import sys

arg1 = sys.argv[1]
print("arg1 =", arg1);
# 获取时间戳 ✅
# SH_DATE=$(TZ=':Asia/Shanghai' date '+%Y-%m-%d %T');
# datetime = $SH_DATE
print("⏰ current datetime =", datetime);
# $ pinout 命令查看,或 https://pinout.xyz/
# 指定 BCM 模式下的 GPIO 针脚编号是 12
# 对应的物理针脚编号是 32
PIN = 12
# BCM 模式
GPIO.setmode(GPIO.BCM)

# 指定 GPIO 针脚为一个电流输出针脚
GPIO.setup(PIN, GPIO.OUT)

# 输出低电平
GPIO.output(PIN, GPIO.LOW)

# index
i = 0
# max
# n = 7

# 类型转换,str => int
n = int(arg1)

print("n =", n)
print('开始闪烁⏳')

while (i < n):
    print("i =", i)
    # 高电平,LED 点亮
    GPIO.output(PIN, GPIO.HIGH)
    # 休眠 1 秒,防止 LED 长时间点亮烧坏了
    time.sleep(1.0)
    # 低电平,LED 熄灭
    GPIO.output(PIN, GPIO.LOW)
    # 休眠 1 秒
    time.sleep(1.0)
    i = i + 1

# 输出低电平,LED 关闭
# GPIO.output(PIN, GPIO.LOW)

# 清除,释放内存
GPIO.cleanup()

print('结束闪烁 👌🏻')

Python 时间戳/日期 格式化

import locale, datetime
import time

def func():
  # 查看有哪些可以使用的 locale 安装包
  # $ locale -a
  # 指定 locale 安装包
  # 存在 locale 安装包 zh_CN.UTF-8 ✅
  locale.setlocale(locale.LC_ALL, 'zh_CN.UTF-8')
  # locale.Error: unsupported locale setting ❌ macOS 不存在 locale 安装包 zh_CN.utf8
  # locale.setlocale(locale.LC_ALL, 'zh_CN.utf8')
  # now = time.time()
  now = "1. 二月 2023"
  rule = '%d. %B %Y'
  format_time = datetime.datetime.strptime(str(now), rule)
  print("formattime format() =", "{}".format(format_time))
  print("formattime =", format_time)
  # 恢复默认的 locale
  locale.resetlocale()

if __name__ == '__main__':
  func()

# $ python ./locale-datetime.py
# formattime format() = 2023-02-01 00:00:00
# formattime = 2023-02-01 00:00:00

locale

macOS zh_CN.UTF-8

$ locale
LANG="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL=

$ locale -a | grep "zh_CN"
zh_CN.UTF-8
zh_CN.GB2312
zh_CN.GBK
zh_CN.GB18030
zh_CN
zh_CN.eucCN

$ locale -a | grep "zh_CN.UTF-8"
zh_CN.UTF-8

Raspberry Pi zh_CN.utf8

pi@raspberrypi:~/Desktop $ locale -a
C
C.UTF-8
en_GB.utf8
POSIX
zh_CN
zh_CN.gb18030
zh_CN.gb2312
zh_CN.gbk
zh_CN.utf8
pi@raspberrypi:~/Desktop $ cat /etc/locale.gen 
# This file lists locales that you wish to have built. You can find a list
# of valid supported locales at /usr/share/i18n/SUPPORTED, and you can add
# user defined locales to /usr/local/share/i18n/SUPPORTED. If you change
# this file, you need to rerun locale-gen.
#
# ...
en_GB.UTF-8 UTF-8
# ... 省略掉了没有安装的 locale 包
zh_CN GB2312
zh_CN.GB18030 GB18030
zh_CN.GBK GBK
zh_CN.UTF-8 UTF-8
# zh_HK.UTF-8 UTF-8
# zh_SG.UTF-8 UTF-8
# zh_TW.UTF-8 UTF-8
# ...

pi@raspberrypi:~/Desktop $ locale
LANG=zh_CN.UTF-8
LANGUAGE=
LC_CTYPE="zh_CN.UTF-8"
LC_NUMERIC="zh_CN.UTF-8"
LC_TIME="zh_CN.UTF-8"
LC_COLLATE="zh_CN.UTF-8"
LC_MONETARY="zh_CN.UTF-8"
LC_MESSAGES="zh_CN.UTF-8"
LC_PAPER="zh_CN.UTF-8"
LC_NAME="zh_CN.UTF-8"
LC_ADDRESS="zh_CN.UTF-8"
LC_TELEPHONE="zh_CN.UTF-8"
LC_MEASUREMENT="zh_CN.UTF-8"
LC_IDENTIFICATION="zh_CN.UTF-8"
LC_ALL=

image

datetime & time

Python packages

https://docs.python.org/3/library/datetime.html

https://docs.python.org/3/library/time.html#module-time

# import datetime

from datetime import datetime

print("datatime =", datetime)

now = datetime.now()

print('⏰ now =', now)

https://www.programiz.com/python-programming/datetime

https://www.geeksforgeeks.org/python-datetime-module/

Python REPL

https://www.w3schools.com/python/trypython.asp?filename=demo_datetime1

Python 将时间戳转换为指定格式日期

  1. time
import time
 
# 获得当前时间时间戳
now = int(time.time())

#转换为其他日期格式,如:"%Y-%m-%d %H:%M:%S"
timeArray = time.localtime(now)

otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(otherStyleTime)

# 执行以上代码输出结果为:
2019-05-21 18:02:49
  1. datetime
import datetime

# 获得当前时间
now = datetime.datetime.now()

# 转换为指定的格式
otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")
print(otherStyleTime)

# 执行以上代码输出结果为:
2019-05-21 18:03:48

https://www.runoob.com/?s=python+date

https://www.runoob.com/python/att-time-strftime.html

https://www.runoob.com/python3/python-timstamp-str.html

https://www.runoob.com/python3/python3-get-yesterday.html

refs

https://www.cnblogs.com/xgqfrms/p/17308980.html

https://www.cnblogs.com/xgqfrms/p/17302589.html#5167058



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @   xgqfrms  阅读(22)  评论(5编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
历史上的今天:
2022-04-12 npm multi script execute concurrently All In One
2022-04-12 Blob & readableStream All In One
2022-04-12 Fetch API & HTTP Response opaque All In One
2021-04-12 React & Accessibility
2021-04-12 React.forwardRef() & React.useRef() & refs
2021-04-12 Chrome & requests throttled background
2021-04-12 js for...of index error All In One
点击右上角即可分享
微信分享提示