最新消息:20190717 VPS服务器:Vultr新加坡,WordPress主题:大前端D8,统一介绍入口:关于

【已解决】Python中获取带毫秒的时间戳

Python crifan 970浏览 0评论

折腾:

【已解决】PySpider中下载mov文件出错:requests.exceptions.HTTPError HTTP 403 Forbidden

期间,需要去获取带毫秒的13位数的时间戳,比如:

<code>#(2)http://xxx.cn/video/54333
# interface: Vod_Api_GetPlayInfo
# 1: 1
# file_id: 7447398155847467190
# app_id: 1252879503
# refer: xxx.com.cn
# _: 1531464292921
# callback: qcvideo_1531464290730_callback1
</code>

中的:

1531464292921

而之前自己的python库:

util/crifanLib/crifanDatetime.py

<code>from datetime import datetime,timedelta
import time

def getCurTimestamp():
    """
    get current time's timestamp
        eg: 1351670162
    """
    return datetimeToTimestamp(datetime.now())


def datetimeToTimestamp(datetimeVal) :
    """
        convert datetime value to timestamp
        eg:
            "2006-06-01 00:00:00" -&gt; 1149091200
    :param datetimeVal:
    :return:
    """
    return int(time.mktime(datetimeVal.timetuple()))
</code>

只能获取不带毫秒的,10位数的时间戳

python timestamp with milliseconds

datetime – Get current time in milliseconds in Python? – Stack Overflow

Convert python datetime to timestamp in milliseconds – Stack Overflow

Python Exercise: Get current time in milliseconds – w3resource

Generating Timestamps that Include Milliseconds

去查查timetuple

python timetuple

Python-基础-时间日期处理小结

https://docs.python.org/2/library/datetime.html

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

python 时间模块小结(time and datetime) | 不懂真人

没有找到更加清楚的解释

不过自己从

https://peiqiang.net/2014/08/15/python-time-and-datetime.html

“In [57]: datetime.datetime.now().timetuple()

Out[57]: time.struct_time(tm_year=2014, tm_mon=8, tm_mday=15, tm_hour=9, tm_min=58, tm_sec=12, tm_wday=4, tm_yday=227, tm_isdst=-1)

In [58]: time.mktime(datetime.datetime.now().timetuple())

Out[58]: 1408067904.0″

以及timetuple名字看出来是:

把time以tuple元组的方式输出了年月日时分秒,但是没有millisecond毫秒

不过自己调试期间发现,即使此处用Python 2,datetime也直接有microsecond微秒:

所以可以直接拿来使用了。

后来看到:

https://docs.python.org/2/library/datetime.html

datetime.timetuple()

Return a time.struct_time such as returned by time.localtime()d.timetuple() is equivalent to time.struct_time((d.year, d.month,d.day, d.hour, d.minute, d.second, d.weekday(), yday, dst)), where yday = d.toordinal() – date(d.year, 1, 1).toordinal() + 1 is the day number within the current year starting with 1 for January 1st. The tm_isdst flag of the result is set according to the dst()method: tzinfo is None or dst() returns Nonetm_isdst is set to -1; else if dst() returns a non-zero value, tm_isdst is set to 1; else tm_isdst is set to 0.

果然是没有毫秒(或微秒)的

https://docs.python.org/2/library/datetime.html#datetime.datetime.microsecond

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

datetime.microsecond

In range(1000000).

嗯 python 2和python 3都有这个属性。

【总结】

可以放心去利用datetime.microsecond去实现带毫秒的时间戳了:

<code>from datetime import datetime,timedelta
import time

def getCurTimestamp(withMilliseconds=False):
    """
    get current time's timestamp
        (default)not milliseconds -&gt; 10 digits: 1351670162
        with milliseconds -&gt; 13 digits: 1531464292921
    """
    curDatetime = datetime.now()
    return datetimeToTimestamp(curDatetime, withMilliseconds)


def datetimeToTimestamp(datetimeVal, withMilliseconds=False) :
    """
        convert datetime value to timestamp
        eg:
            "2006-06-01 00:00:00.123" -&gt; 1149091200
            if with milliseconds -&gt; 1149091200123
    :param datetimeVal:
    :return:
    """
    timetupleValue = datetimeVal.timetuple()
    timestampFloat = time.mktime(timetupleValue) # 1531468736.0 -&gt; 10 digits
    timestamp10DigitInt = int(timestampFloat) # 1531468736
    timestampInt = timestamp10DigitInt

    if withMilliseconds:
        microsecondInt = datetimeVal.microsecond # 817762
        microsecondFloat = float(microsecondInt)/float(1000000) # 0.817762
        timestampFloat = timestampFloat + microsecondFloat # 1531468736.817762
        timestampFloat = timestampFloat * 1000 # 1531468736817.7621 -&gt; 13 digits
        timestamp13DigitInt = int(timestampFloat) # 1531468736817
        timestampInt = timestamp13DigitInt

    return timestampInt

def testTimestamp():
    # test timestamp with milliseconds
    timestampNoMilliSec = getCurTimestamp()
    print("timestampNoMilliSec=%s" % timestampNoMilliSec) # 1531468833
    timestampWithMilliSec = getCurTimestamp(withMilliseconds=True)
    print("timestampWithMilliSec=%s" % timestampWithMilliSec) # 1531468833344
</code>

最新代码详见:

https://github.com/crifan/crifanLibPython/blob/master/crifanLib/crifanDatetime.py

转载请注明:在路上 » 【已解决】Python中获取带毫秒的时间戳

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
62 queries in 0.242 seconds, using 18.92MB memory