2017年2月19日 星期日

[ Python 常見問題 ] How to set timezone to eastern for DateTime module in python?

Source From Here
Question
I'm utilizing the datetime module to produce the current date. Is any way to setup the different timezone in this module?

How-To
Your date is a "naive" datetime, it doesn't have a timezone (tz=None). Then you have to localize this datetime by setting a timezone. Use pytz module to do that.
>>> from datetime import datetime
>>> from pytz import timezone
>>> fmt = '%Y-%m-%d %H:%M:%S %Z%z'
>>> print "Native timezone: %s" % datetime.now().strftime(fmt)
Native timezone: 2017-02-19 16:45:25
>>> print "Timezone(US/Eastern): %s" % datetime.now(eastern_tz).strftime(fmt)
Timezone(US/Eastern): 2017-02-19 03:45:29 EST-0500

From the Linux, you can check your default timezone by (Take CentOS7 for example):
# date +'%:z %Z'
+08:00 CST
# ls -hl /etc/localtime
lrwxrwxrwx. 1 root root 33 Oct 7 09:16 /etc/localtime -> ../usr/share/zoneinfo/Asia/Taipei


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...