【发布时间】:2021-11-30 01:39:55
【问题描述】:
我没有多少 Python 编程经验,但需要将当前时间以某种 12 小时格式从几个不同的时区导出到单个文本文件中。我找到了几种解决方案,但需要将所有三个组件集成到一个解决方案中。
from datetime import datetime
"{:%A, %B %d %Y %I:%M:%S %p %Z}".format(datetime.now())
import datetime
import pytz
my_date = datetime.datetime.now(pytz.timezone('UTC'))
print(my_date)
my_date = datetime.datetime.now(pytz.timezone('America/New_York'))
print(my_date)
my_date = datetime.datetime.now(pytz.timezone('EST'))
print(my_date)
my_date = datetime.datetime.now(pytz.timezone('Pacific/Port_Moresby'))
print(my_date)
import datetime
open("C:\temp\current_time.txt", "w").write("UTC Time: ")
open("C:\temp\current_time.txt", "a").write(datetime.datetime.now().ctime()+ '\n')
open("C:\temp\current_time.txt", "a").write("EST Time: ")
open("C:\temp\current_time.txt", "a").write(datetime.datetime.now().ctime()+ '\n')
open("C:\temp\current_time.txt", "a").write("New York Time: ")
open("C:\temp\current_time.txt", "a").write(datetime.datetime.now().ctime()+ '\n')
open("C:\temp\current_time.txt", "a").write("Port Moresby Time: ")
open("C:\temp\current_time.txt", "a").write(datetime.datetime.now().ctime())
最后一个序列似乎在 Python 3.7 中不起作用,但如果可能的话,希望它使用(不幸的是)Python 2.7 安装来工作。
最终,我想要这些结果:
UTC Time: Monday, October 11, 2021 09:05:17
EST Time: Monday, October 11, 2021 04:05:17 AM
New York Time: Monday, October 11, 2021 05:05:17 AM
Port Moresby Time: Monday, October 11, 2021 07:05:17 PM
非常感谢您的帮助。
【问题讨论】:
-
请注意,
%Z不会给您time zone name,而只是一个缩写(由于模棱两可,可能有点没用)。
标签: python python-2.7 datetime format timezone