python3 中当地时间输出,将时区感知日期时间转换为Python中的本地时间

How do you convert a timezone-aware datetime object to the equivalent non-timezone-aware datetime for the local timezone?

My particular application uses Django (although, this is in reality a generic Python question):

import iso8601

....

date_str="2010-10-30T17:21:12Z"

....

d = iso8601.parse_date(date_str)

foo = app.models.FooModel(the_date=d)

foo.save()

This causes Django to throw an error:

raise ValueError("MySQL backend does not support timezone-aware datetimes.")

What I need is:

d = iso8601.parse_date(date_str)

local_d = SOME_FUNCTION(d)

foo = app.models.FooModel(the_date=local_d)

What would SOME_FUNCTION be?

解决方案

In general, to convert an arbitrary timezone-aware datetime to a naive (local) datetime, I'd use the pytz module and astimezone to convert to local time, and replace to make the datetime naive:

In [76]: import pytz

In [77]: est=pytz.timezone('US/Eastern')

In [78]: d.astimezone(est)

Out[78]: datetime.datetime(2010, 10, 30, 13, 21, 12, tzinfo=)

In [79]: d.astimezone(est).replace(tzinfo=None)

Out[79]: datetime.datetime(2010, 10, 30, 13, 21, 12)

But since your particular datetime seems to be in the UTC timezone, you could do this instead:

In [65]: d

Out[65]: datetime.datetime(2010, 10, 30, 17, 21, 12, tzinfo=tzutc())

In [66]: import datetime

In [67]: import calendar

In [68]: datetime.datetime.fromtimestamp(calendar.timegm(d.timetuple()))

Out[68]: datetime.datetime(2010, 10, 30, 13, 21, 12)

By the way, you might be better off storing the datetimes as naive UTC datetimes instead of naive local datetimes. That way, your data is local-time agnostic, and you only convert to local-time or any other timezone when necessary. Sort of analogous to working in unicode as much as possible, and encoding only when necessary.

So if you agree that storing the datetimes in naive UTC is the best way, then all you'd need to do is define:

local_d = d.replace(tzinfo=None)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值