使用 strftime 将 python 日期时间转换为纪元 [英] Convert python datetime to epoch with strftime

查看:48
本文介绍了使用 strftime 将 python 日期时间转换为纪元的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UTC 时间,我想从中获得自纪元以来的秒数.

我正在使用 strftime 将其转换为秒数.以2012年4月1日为例.

>>>datetime.datetime(2012,04,01,0,0).strftime('%s')'1333234800'

2012 年 4 月 1 日 UTC 从纪元开始是 1333238400,但上面返回 1333234800,相差 1 小时.

所以看起来 strftime 正在考虑我的系统时间并在某处应用时区转换.我认为 datetime 纯粹是幼稚的?

我怎样才能解决这个问题?如果可能,除非标准,否则避免导入其他库.(我有便携性问题).

解决方案

如果您想将 python 日期时间转换为自纪元以来的秒数,您可以明确地进行:

<预><代码>>>>(datetime.datetime(2012,04,01,0,0) - datetime.datetime(1970,1,1)).total_seconds()1333238400.0

在 Python 3.3+ 中,您可以使用 timestamp() 代替:

<预><代码>>>>datetime.datetime(2012,4,1,0,0).timestamp()1333234800.0


为什么不应该使用 datetime.strftime('%s')

Python 实际上并不支持 %s 作为 strftime 的参数(如果您查看 http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior 它不在列表中),它工作的唯一原因是因为 Python 正在通过到您系统的 strftime 的信息,它使用您的本地时区.

<预><代码>>>>datetime.datetime(2012,04,01,0,0).strftime('%s')'1333234800'

I have a time in UTC from which I want the number of seconds since epoch.

I am using strftime to convert it to the number of seconds. Taking 1st April 2012 as an example.

>>>datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'

1st of April 2012 UTC from epoch is 1333238400 but this above returns 1333234800 which is different by 1 hour.

So it looks like that strftime is taking my system time into account and applies a timezone shift somewhere. I thought datetime was purely naive?

How can I get around that? If possible avoiding to import other libraries unless standard. (I have portability concerns).

解决方案

If you want to convert a python datetime to seconds since epoch you could do it explicitly:

>>> (datetime.datetime(2012,04,01,0,0) - datetime.datetime(1970,1,1)).total_seconds()
1333238400.0

In Python 3.3+ you can use timestamp() instead:

>>> datetime.datetime(2012,4,1,0,0).timestamp()
1333234800.0


Why you should not use datetime.strftime('%s')

Python doesn't actually support %s as an argument to strftime (if you check at http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior it's not in the list), the only reason it's working is because Python is passing the information to your system's strftime, which uses your local timezone.

>>> datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'

这篇关于使用 strftime 将 python 日期时间转换为纪元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆