【问题标题】:Python File Modified Time get and set over socketPython文件修改时间通过套接字获取和设置
【发布时间】:2012-11-03 14:36:38
【问题描述】:

我已经编写了一些代码来获取文件的修改时间

os.path.getmtime('path')

它返回一些像965465464.19234 这样的数字。我将其转换为字节并通过套接字发送。在另一端,我读取了套接字并尝试将此时间戳设置为另一个文件:

os.utime('path',(access_time, modified_time))

当我尝试设置从套接字接收的modified_time 时,我确保access_time 保持不变。但是utime 需要一个整数,所以我截断了这个数字(例如:965465464)然后一切正常。

我会因为截断而失去任何东西吗?怎样才能做得更好?

【问题讨论】:

    标签: python file time python-3.x


    【解决方案1】:

    我认为问题与 modified_time 是浮点数或整数无关。下面的代码应该可以工作。我做了所有事情,但通过网络发送。

    import os
    from datetime import datetime
    from calendar import timegm
    import sys
    st_info = os.stat('foo.py')
    st_info.st_atime #acces time
    st_info.st_mtime #modified time
    mtime = st_info.st_mtime
    atime = st_info.st_atime
    # send over the wire
    os.utime('foo.py', (atime, mtime))
    

    如您所见,os.utime 可以很好地处理浮点数。

    时间

    输出[15]:1322517342.0

    在[16]中:类型(mtime)

    输出[16]:浮动

    【讨论】:

    • 有点疑问,为了在 python 3 中进行转换,通过套接字发送要求我们将所有内容转换为字节,然后从字节返回到任何预期的内容。正确的?那么 int 和 float 的问题不会出现吗?感谢您的回复。感谢您的帮助
    • 文档明确表示:“如果您需要确切的时间戳,您应该始终使用 st_atime_ns、st_mtime_ns 和 st_ctime_ns”。据我了解,OP 想要确切的时间戳,因此应该使用整数 *_ns 属性。
    【解决方案2】:

    getmtime() 返回st_mtime。来自the docs

    注意:st_atime、st_mtime、和 st_ctime 属性取决于操作系统和文件 例如,在使用 FAT 或 FAT32 文件的 Windows 系统上 系统,st_mtime 有 2 秒的分辨率,而 st_atime 只有 1 天 解决。有关详细信息,请参阅您的操作系统文档。 同样,虽然 st_atime_ns、st_mtime_ns 和 st_ctime_ns 总是以纳秒表示,许多系统不提供 纳秒精度。在确实提供纳秒精度的系统上, 用于存储 st_atime、st_mtime 和 st_ctime 不能保留所有这些,因此会稍微 不准确。 如果您需要确切的时间戳,您应该始终使用 st_atime_ns、st_mtime_ns 和 st_ctime_ns。

    强调我的

    您可以使用ns 参数将整数纳秒从os.stat() 传递到os.utime()

    os.utime(path, ns=(access_time_ns, modified_time_ns))
    

    【讨论】:

      猜你喜欢
      • 2012-07-07
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 2015-08-28
      • 2021-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多