获取当前日期小时的时间戳
好的,我需要一种方法来获取今天某个时间的时间戳。
举个例子,我想要今天晚上7:30的Unix时间戳——我该怎么做才能得到这个值?在PHP中可以用strtotime()来实现,但我不太确定在Python中该怎么做。
补充说明:我指的是今天的时间而不是固定写死的某一天。所以如果我明天运行这个脚本,它会返回明天晚上7:30的时间戳。
3 个回答
0
你可以使用时间模块:
from datetime import datetime
from time import mktime
# like said Ashoka
ts = datetime.strptime("2014-7-7 7:30","%Y-%m-%d %H:%M")
#you have now your datetime object
print mktime(ts.timetuple())
# print 1404711000.0
print int(mktime(ts.timetuple()))
# print 1404711000
要注意的是,mktime这个函数不考虑时区,所以如果你想要使用UTC时区的时间,记得在使用时间之前先转换日期:
import pytz
fr = pytz.timezone('Europe/Paris')
#localize
ts = fr.localize(ts)
#timestamp in UTC
mktime(ts.astimezone(pytz.UTC).timetuple())
0
calendar.timegm 方法可以根据你传入的时间元组返回一个时间戳:
import calendar
from datetime import datetime
d = datetime(year=2014, month=7, day=8, hour=7, minute=30)
calendar.timegm(d.utctimetuple())
# 1404804600
datetime.utcfromtimestamp(calendar.timegm(d.utctimetuple()))
# datetime.datetime(2014, 7, 8, 7, 30)
这里有两个重要的东西,分别是 utctimetuple
和 utcfromtimestamp
。你肯定希望得到的是一个UTC时间戳,而不是你所在时区的时间戳。
import calendar
from datetime import datetime
from pytz import timezone, utc
tz = timezone('Europe/Warsaw')
aware = datetime(year=2014, month=7, day=8, hour=7, minute=30)
aware = tz.localize(aware)
# datetime.datetime(2014, 7, 8, 7, 30, tzinfo=<DstTzInfo 'Europe/Warsaw' CEST+2:00:00 DST>)
stamp = calendar.timegm(aware.utctimetuple())
# 1404797400
d = datetime.utcfromtimestamp(stamp)
# datetime.datetime(2014, 7, 8, 5, 30)
d = d.replace(tzinfo=utc)
d.astimezone(tz)
# datetime.datetime(2014, 7, 8, 7, 30, tzinfo=<DstTzInfo 'Europe/Warsaw' CEST+2:00:00 DST>)
1
在编程中,有时候我们需要处理一些数据,比如从一个地方获取数据,然后把它用在另一个地方。这个过程就像是把水从一个水桶倒到另一个水桶里。我们需要确保水不会洒出来,也就是在转移数据时要保持数据的完整性。
有些时候,数据的格式可能会不一样,就像是一个水桶的口比较大,而另一个水桶的口比较小。我们需要找到合适的方法来把水顺利地倒过去,这样才能避免浪费。
在编程中,这种数据的转移和格式的转换通常会用到一些工具和函数。它们就像是帮助我们把水从一个桶倒到另一个桶的漏斗,确保一切顺利进行。
总之,处理数据就像是搬运水,确保每一步都小心翼翼,才能让我们的程序运行得更好。
from datetime import datetime
now = datetime.utcnow() # Current time
then = datetime(1970,1,1) # 0 epoch time
ts = now - then
ts = ts.days * 24 * 3600 + ts.seconds
# alternatively, per Martijn Pieters
ts = int(ts.total_seconds())