问题:使用strftime将python datetime转换为纪元

我在UTC有一个时间,我想要从纪元开始经过的秒数。

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

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

从纪元开始的UTC时间为2012年4月1日,但以上返回1333234800,相差1小时。

因此,看来strftime正在考虑我的系统时间,并在某处应用了时区偏移。我以为日期时间纯粹是天真的?

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

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


回答 0

如果要将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'

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'

回答 1

我在时区等方面遇到了严重问题。Python处理所有事情的方式(对我而言)非常令人困惑。事情似乎使用日历模块(参见链接被精细工作1234)。

>>> import datetime
>>> import calendar
>>> aprilFirst=datetime.datetime(2012, 04, 01, 0, 0)
>>> calendar.timegm(aprilFirst.timetuple())
1333238400

I had serious issues with Timezones and such. The way Python handles all that happen to be pretty confusing (to me). Things seem to be working fine using the calendar module (see links 1, 2, 3 and 4).

>>> import datetime
>>> import calendar
>>> aprilFirst=datetime.datetime(2012, 04, 01, 0, 0)
>>> calendar.timegm(aprilFirst.timetuple())
1333238400

回答 2

import time
from datetime import datetime
now = datetime.now()

time.mktime(now.timetuple())
import time
from datetime import datetime
now = datetime.now()

time.mktime(now.timetuple())

回答 3

import time
from datetime import datetime
now = datetime.now()

# same as above except keeps microseconds
time.mktime(now.timetuple()) + now.microsecond * 1e-6

(对不起,它不会让我对现有答案发表评论)

import time
from datetime import datetime
now = datetime.now()

# same as above except keeps microseconds
time.mktime(now.timetuple()) + now.microsecond * 1e-6

(Sorry, it wouldn’t let me comment on existing answer)


回答 4

如果您只需要使用unix / epoch时间的时间戳,则此行可以工作:

created_timestamp = int((datetime.datetime.now() - datetime.datetime(1970,1,1)).total_seconds())
>>> created_timestamp
1522942073L

并且仅取决于datetime python2和python3中的作品

if you just need a timestamp in unix /epoch time, this one line works:

created_timestamp = int((datetime.datetime.now() - datetime.datetime(1970,1,1)).total_seconds())
>>> created_timestamp
1522942073L

and depends only on datetime works in python2 and python3


回答 5

这适用于Python 2和3:

>>> import time
>>> import calendar
>>> calendar.timegm(time.gmtime())
1504917998

仅遵循官方文档… https://docs.python.org/2/library/time.html#module-time

This works in Python 2 and 3:

>>> import time
>>> import calendar
>>> calendar.timegm(time.gmtime())
1504917998

Just following the official docs… https://docs.python.org/2/library/time.html#module-time


回答 6

对于明确的时区独立解决方案,请使用pytz库。

import datetime
import pytz

pytz.utc.localize(datetime.datetime(2012,4,1,0,0), is_dst=False).timestamp()

输出(浮动):1333238400.0

For an explicit timezone-independent solution, use the pytz library.

import datetime
import pytz

pytz.utc.localize(datetime.datetime(2012,4,1,0,0), is_dst=False).timestamp()

Output (float): 1333238400.0


回答 7

在Python 3.7中

以date.isoformat()和datetime.isoformat()发出的格式之一返回与date_string对应的datetime。具体来说,此函数支持格式为YYYY-MM-DD [* HH [:MM [:SS [.fff [fff]]]] [+ HH:MM [:SS [.ffffff]]]]的字符串,其中*可以匹配任何单个字符。

https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat

In Python 3.7

Return a datetime corresponding to a date_string in one of the formats emitted by date.isoformat() and datetime.isoformat(). Specifically, this function supports strings in the format(s) YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]], where * can match any single character.

https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。