Noe*_*oel 193 python datetime utc strftime epoch
我有一段时间在UTC,从那里我想要自纪元以来的秒数.
我使用strftime将其转换为秒数.以2012年4月1日为例.
>>>datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'
Run Code Online (Sandbox Code Playgroud)
2012年4月1日UTC的纪元是1333238400但是这个上面返回1333234800,相差1小时.
所以看起来strftime正在考虑我的系统时间并在某个地方应用时区转换.我以为datetime纯粹是天真的?
我怎么能绕过那个?如果可能的话,避免导入其他库,除非标准.(我有可移植性问题).
jle*_*ahy 356
如果你想将python日期时间转换为epoch以来的秒数,你可以明确地做到:
>>> (datetime.datetime(2012,04,01,0,0) - datetime.datetime(1970,1,1)).total_seconds()
1333238400.0
Run Code Online (Sandbox Code Playgroud)
在Python 3.3+中你可以使用timestamp()
:
>>> datetime.datetime(2012,4,1,0,0).timestamp()
1333234800.0
Run Code Online (Sandbox Code Playgroud)
为什么你不应该使用 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'
Run Code Online (Sandbox Code Playgroud)
Bor*_*jaX 99
我和Timezones等有严重的问题.Python处理所有碰巧相当令人困惑的方式(对我而言).事情似乎使用日历模块(参见链接被精细工作1,2,3和4).
>>> import datetime
>>> import calendar
>>> aprilFirst=datetime.datetime(2012, 04, 01, 0, 0)
>>> calendar.timegm(aprilFirst.timetuple())
1333238400
Run Code Online (Sandbox Code Playgroud)
sro*_*oss 33
import time
from datetime import datetime
now = datetime.now()
time.mktime(now.timetuple())
Run Code Online (Sandbox Code Playgroud)
Cha*_*ger 15
import time
from datetime import datetime
now = datetime.now()
# same as above except keeps microseconds
time.mktime(now.timetuple()) + now.microsecond * 1e-6
Run Code Online (Sandbox Code Playgroud)
(对不起,它不会让我对现有答案发表评论)
如果您只需要 unix /epoch 时间的时间戳,则这一行有效:
created_timestamp = int((datetime.datetime.now() - datetime.datetime(1970,1,1)).total_seconds())
>>> created_timestamp
1522942073L
Run Code Online (Sandbox Code Playgroud)
并且只依赖datetime
于 python2 和 python3 中的作品
归档时间: |
|
查看次数: |
272140 次 |
最近记录: |