惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Fortinet All Blogs
博客园 - 三生石上(FineUI控件)
小众软件
小众软件
人人都是产品经理
人人都是产品经理
V
Visual Studio Blog
Last Week in AI
Last Week in AI
V
V2EX
博客园_首页
IT之家
IT之家
Jina AI
Jina AI
博客园 - 叶小钗
The Cloudflare Blog
T
Tailwind CSS Blog
腾讯CDC
B
Blog
D
Docker
L
LangChain Blog
博客园 - 司徒正美
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
美团技术团队
Apple Machine Learning Research
Apple Machine Learning Research
爱范儿
爱范儿
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
GbyAI
GbyAI

jdhao's digital space

Conversion between base64 and OpenCV or PIL Image 腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN
Get Current Time with Time Zone Info in Python
2020-04-17 · via jdhao's digital space

I am trying to generate a custom time format using the Python datetime package. My original code is:

from datetime import datetime

print(datetime.now().strftime("%Y-%m-%d %H:%M:%S%z"))

Strangely, the time zone field %z is not present in the generated time string. The generated string is like:

‘2020-04-17 20:41:35’

I checked the documentation of strftime(), and the meaning of %z is:

UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if the object is naive).

Here, we need to understand what is a naive or aware time object. Simply put, a naive time object has no timezone info, thus is incomplete. On other hand, an awaretime object has timezone info and is complete. A full explanation can be found here.

By default, the time object we get from datetime.now() is a naive object, thus having no timezone info attached. To convert the time object to an aware object with our local time zone info, we can use datetime.astimezone():

aware_time = datetime.now().astimezone()
print(aware_time.strftime("%Y-%m-%d %H:%M:%S%z"))

Now, we will get the expected result:

2020-04-17 20:53:13+0800

References#