从服务器获取的时间戳本地时间戳
below is the Scenario:
1. (Host-machine)User will create tasks on the server by sending task information to the rest services of server (task_name,task_owner etc)
2. (server-machine)server will receive information from the user and creates a timestamp(2017-08-07 08:42:07-04:00) along with timezone for the task and saves into a database
3. user will do list tasks and user must be able to see task_name,task_owner and task_creation time
Assuming Host-machine and server-machine are on different timezones.
when user does list tasks we trigger the rest-services and processes the tasks timestamps and show local timestamps equivalent to server timezone.
我的主机的机器代码使用Python来触发REST的服务和解析结果..从服务器获取的时间戳本地时间戳
so,
input: 2017-08-07 08:42:07-04:00
output : 2017-08-07 17:30:03
explanation: its converting from time stamp of one time zone to
another timezone.EDT is 2017-08-07 08:42:07-04:00
IST is 2017-08-07 08:42:07+5:30 .
so, assume Local is IST the time must be ~17:30
(8:42:07+9:30)
新蜂到Python帮我出:)
我认为Arrow可以帮助你在你想要做的事情中变得更简单。服务器上的所有日期和时间都应使用UTC,并为每个用户保存正确的时区。使用arrow
你可以简单地使用:
import arrow
time = arrow.get(input_time, 'YYYY-MM-DD HH:mm:ssZZ')
print time.to('local')
感谢您的评论。他们将在数据库中使用UTC,但我们使用主机上的其余服务查询数据库。时间戳将更改为主机的本地时区。因此,服务器最终将返回带有主机时区的时间戳。因此该值可以是任何时区。仅供参考,MySQL使用与UTC时间戳相同的方式存储时间戳,在获取结果时,它将修改计算机时区的时间戳在哪里查询数据库可能是预期的行为。让我知道如果我出错 –
我真的不明白你最近的评论,也不明白我是否真的解决了你的困境:) – droravr
fixed this using the package called **tzlocal**
def convert_date_format(self, server_time):
local_date =parse(server_time).astimezone(get_localzone())
return str(local_date.replace(microsecond=0, tzinfo=None))
**explanation**
input: "2017-08-08 15:35:27-4:00"
1.function takes server_time as input converts to datetime object using
parse()
2.get_localzone() will fetch the local time zone
3.using the astimezone() converted the server_time to local timestamp
4.removed the microseconds and timezone fields
怎么比只用'arrow.get(input).to( '本地')'? – droravr
@droravr它不容易,两者都是类似的,我已经使用tzlocal来处理时区挑战。我不想使用另一个包(箭头),因为我已经使用tzlocal服务于我的目的。 –
的可能的复制[?如何转换字符串日期时间在Python时间戳(https://stackoverflow.com/questions/10957522/how-to-convert-字符串日期时间到时间戳在蟒蛇) – Thomas
@ThomasMey这不是一个重复!因为您共享的帖子将字符串转换为同一时间+偏移量的时间戳对象。但我的问题是从一个时区的时间戳转换到另一个时区。 EDT是2017-08-07 08:42:07-04:00 IST是2017-08-07 08:42:07 + 5:30。可以说本地是IST,时间一定是〜9:30(8 :42:07 + 9:30)。 python中有没有这样的方法来实现这个用例? –
任何人都知道答案的答案..这将是伟大的!提前致谢。 –