如何将本地时间的日期时间字符串转换为UTC时间的字符串?
我确定我以前做过这个,但找不到它,所以希望能帮助我(以及其他人)在将来做到这一点.
澄清:例如,如果我2008-09-17 14:02:00
在我的本地时区(+10
)中,我想生成一个具有相同UTC
时间的字符串:2008-09-17 04:02:00
.
此外,请访问http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/,请注意,一般情况下这不可能与DST和其他问题一样,因此从当地时间到UTC时间.
我正在处理Python中的日期,我需要将它们转换为UTC时间戳,以便在Javascript中使用.以下代码不起作用:
>>> d = datetime.date(2011,01,01)
>>> datetime.datetime.utcfromtimestamp(time.mktime(d.timetuple()))
datetime.datetime(2010, 12, 31, 23, 0)
Run Code Online (Sandbox Code Playgroud)
将日期对象首先转换为datetime也无济于事.我试过这个链接的例子,但是:
from pytz import utc, timezone
from datetime import datetime
from time import mktime
input_date = datetime(year=2011, month=1, day=15)
Run Code Online (Sandbox Code Playgroud)
现在要么:
mktime(utc.localize(input_date).utctimetuple())
Run Code Online (Sandbox Code Playgroud)
要么
mktime(timezone('US/Eastern').localize(input_date).utctimetuple())
Run Code Online (Sandbox Code Playgroud)
确实有效.
所以一般的问题:如何根据UTC获得自纪元以来转换为秒的日期?
time
从epoch开始,模块可以使用秒进行初始化:
>>> import time
>>> t1=time.gmtime(1284286794)
>>> t1
time.struct_time(tm_year=2010, tm_mon=9, tm_mday=12, tm_hour=10, tm_min=19,
tm_sec=54, tm_wday=6, tm_yday=255, tm_isdst=0)
Run Code Online (Sandbox Code Playgroud)
有一种优雅的方式以datetime.datetime
相同的方式初始化对象吗?
我有一个使用datetime.utcnow()创建并保存在数据库中的python datetime实例.
为了显示,我想使用默认的本地时区将从数据库检索的日期时间实例转换为本地日期时间(即,就像使用datetime.now()创建日期时间一样).
如何仅使用python标准库将UTC日期时间转换为本地日期时间(例如,没有pytz依赖项)?
似乎一个解决方案是使用datetime.astimezone(tz),但是如何获得默认的本地时区?
如何从Python更改Windows文件的文件创建日期?
我无法在python中的文件上设置ctime/mtime.首先,我通过ftp获取文件的原始时间戳
我唯一想要的是使用ftplib在我下载的文件上保留原始时间戳.
def getFileTime(ftp,name):
try :
modifiedTime = ftp.sendcmd('MDTM ' + name)
filtid = datetime.strptime(modifiedTime[4:], "%Y%m%d%H%M%S").strftime("%d %B %Y %H:%M:%S")
return filtid
except :
return False
Run Code Online (Sandbox Code Playgroud)
然后我下载文件
def downloadFile(ftp, fileName) :
try:
ftp.retrbinary('RETR %s' % fileName,open(fileName, 'wb').write)
except ftplib.error_perm:
print 'ERROR: cannot read file "%s"' % fileName
os.unlink(fileName)
return False
else:
print '*** Downloaded "%s" to CWD' % fileName
return True
Run Code Online (Sandbox Code Playgroud)
我想将原始时间戳设置为下载的文件
def modifyTimestapToOriginal(fileName, orgTime):
#try:
os.utime(fileName, orgTime)
fileName.close()
# return True
# except:
# return False
Run Code Online (Sandbox Code Playgroud)
这就是我试图这样做的方式
ftp, files = …
Run Code Online (Sandbox Code Playgroud) 我有一个类型的对象datetime.time
.如何将其转换为表示其持续时间的int(以秒为单位)?或者到一个字符串,我可以通过拆分将其转换为第二个表示形式?
根据这个答案的精神,我尝试以下方法将日期时间的DataFrame列转换为自纪元以来的秒数列.
df['date'] = (df['date']+datetime.timedelta(hours=2)-datetime.datetime(1970,1,1))
df['date'].map(lambda td:td.total_seconds())
Run Code Online (Sandbox Code Playgroud)
第二个命令导致以下错误,我不明白.关于这里可能会发生什么的任何想法?我用apply替换了地图,这对事情没有帮助.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-99-7123e823f995> in <module>()
----> 1 df['date'].map(lambda td:td.total_seconds())
/Users/cpd/.virtualenvs/py27-ipython+pandas/lib/python2.7/site-packages/pandas-0.12.0_937_gb55c790-py2.7-macosx-10.8-x86_64.egg/pandas/core/series.pyc in map(self, arg, na_action)
1932 return self._constructor(new_values, index=self.index).__finalize__(self)
1933 else:
-> 1934 mapped = map_f(values, arg)
1935 return self._constructor(mapped, index=self.index).__finalize__(self)
1936
/Users/cpd/.virtualenvs/py27-ipython+pandas/lib/python2.7/site-packages/pandas-0.12.0_937_gb55c790-py2.7-macosx-10.8-x86_64.egg/pandas/lib.so in pandas.lib.map_infer (pandas/lib.c:43628)()
<ipython-input-99-7123e823f995> in <lambda>(td)
----> 1 df['date'].map(lambda td:td.total_seconds())
AttributeError: 'float' object has no attribute 'total_seconds'
Run Code Online (Sandbox Code Playgroud) 我正在使用 Python 3.7 和 Django。我想获取日期时间对象自 1970 年 1 月 1 日以来的秒数(或毫秒)。遵循此处的建议 -在 Python 中,如何将“datetime”对象转换为秒?,我实现了
now = datetime.now()
...
return [len(removed_elts) == 0, score, now.total_seconds()]
Run Code Online (Sandbox Code Playgroud)
但“now.total_seconds()”行给出了错误
AttributeError: 'datetime.datetime' object has no attribute 'total_seconds'
Run Code Online (Sandbox Code Playgroud)
获取自 1970 年 1 月 1 日以来的秒数的正确方法是什么?
我有一个从数据库中获取的日期时间,这个日期时间是一个 UTC 日期时间。但是当我从数据库中提取它时,它不知道时区。我需要做的是将此日期时间转换为另一个函数的“纪元秒数”时间。问题在于,系统的时间在 PST 中,由于特定原因我无法更改它。
所以,我想要做的是,获取我从数据库中获得的这个日期时间,并告诉 python 这个日期时间是一个 UTC 日期时间。我所做的每一种方式都会导致它因时区转换而失去时间或获得时间。同样,不是试图转换时间,只是试图指定它是 UTC。
如果有人可以帮助解决这个问题,那就太好了。
谢谢!
例子
假设 database_function() 返回的日期时间数据类型为 '2013-06-01 01:06:18'
datetime = database_function()
epoch = datetime.strftime('%s')
pytz.utc.localize(database_function()).datetime.strftime('%s')
datetime.replace(tzinfo=pytz.utc).datetime.strftime('%s')
Run Code Online (Sandbox Code Playgroud)
这两个都返回 1370077578 的纪元时间戳但是,它应该返回每个http://www.epochconverter.com/的时间戳 1370048778请 记住,这个时间戳是一个 UTC 时间戳