使用strftime将python datetime转换为epoch [英] Convert python datetime to epoch with strftime

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

问题描述



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

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

2012年4月1日UTC从epoch是1333238400,但这上面返回1333234800不同1小时。



所以看起来strftime正在考虑我的系统时间,并在某处应用时区偏移。我以为datetime是纯天真的?



我该如何解决?如果可以避免导入其他库,除非标准。 (我有可移植性的问题)。

解决方案

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



如果您希望将python datetime转换为秒,那么您应该明确地执行:

 > ;>> datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'
>>> (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


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).

解决方案

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.

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

>>> datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'
>>> (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

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

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