【问题标题】:Convert string date to timestamp in Python在 Python 中将字符串日期转换为时间戳
【发布时间】:2012-03-27 03:03:02
【问题描述】:

如何将"%d/%m/%Y"格式的字符串转换为时间戳?

"01/12/2011" -> 1322697600

【问题讨论】:

  • 第二个数字是多少? Unix 纪元时间?
  • @Hasteur,是的。第二个数字表示从 unix 纪元开始到指定日期之间经过的秒数。这种格式也称为 POSIX 时间。
  • 时间过得真快!你在 13 岁时问过这个问题……现在是 16 岁……

标签: python datetime


【解决方案1】:
>>> int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime("%s"))
1322683200

【讨论】:

【解决方案2】:
>>> import time
>>> import datetime
>>> s = "01/12/2011"
>>> time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple())
1322697600.0

【讨论】:

  • 假定本地时区为 2011 年 1 月 12 日午夜。如果输入是 UTC;你可以使用calendar.timegm() or .toordinal()
  • datetime.datetime.strptime(s, "%d/%m/%Y").timestamp() 有点短
  • @timdiels:再次。如果没有给出明确的时区,.timestamp() 假定 local 时间而不是 UTC。答案中的代码仅在本地时区的UTC偏移量为零的计算机上有效(产生预期的1322697600)。
  • 这不起作用:datetime.datetime.strptime("2014:06:28 11:53:21", "%Y:%m:%d %H:%M:%S ").timestamp() Traceback(最近一次调用最后一次):文件“”,第 1 行,在 AttributeError:'datetime.datetime' 对象没有属性'timestamp'
  • @ZdenekMaxa datetime.timestamp() 仅适用于 python >= 3.3 版本。 docs.python.org/3/whatsnew/3.3.html
【解决方案3】:

首先您必须使用strptime 类将字符串转换为struct_time 格式。

然后只需从那里使用mktime 来获取您的浮动。

【讨论】:

    【解决方案4】:

    答案还取决于您输入的日期时区。如果您的日期是本地日期,那么您可以像 katrielalex 所说的那样使用 mktime() - 只是我不明白他为什么使用 datetime 而不是这个较短的版本:

    >>> time.mktime(time.strptime('01/12/2011', "%d/%m/%Y"))
    1322694000.0
    

    但请注意,我的结果与他的不同,因为我可能在不同的 TZ 中(结果是无时区的 UNIX 时间戳)

    现在,如果输入日期已经是 UTC,那么我认为正确的解决方案是:

    >>> calendar.timegm(time.strptime('01/12/2011', '%d/%m/%Y'))
    1322697600
    

    【讨论】:

    • 我认为这样更好。无需同时导入“时间”和“日期时间”。
    • 如何处理“YYYY-MM-DD”格式的日期?
    【解决方案5】:

    将字符串转换为日期对象:

    from datetime import date, datetime
    
    date_string = "01/12/2011"
    date_object = date(*map(int, reversed(date_string.split("/"))))
    assert date_object == datetime.strptime(date_string, "%d/%m/%Y").date()
    

    将日期对象转换为 POSIX 时间戳的方式取决于时区。来自Converting datetime.date to UTC timestamp in Python

    • 日期对象表示 UTC 的午夜

      import calendar
      
      timestamp1 = calendar.timegm(utc_date.timetuple())
      timestamp2 = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * 24*60*60
      assert timestamp1 == timestamp2
      
    • 日期对象表示当地时间的午夜

      import time
      
      timestamp3 = time.mktime(local_date.timetuple())
      assert timestamp3 != timestamp1 or (time.gmtime() == time.localtime())
      

    时间戳不同,除非 UTC 和当地时间的午夜是同一时间实例。

    【讨论】:

    • 当我运行这篇文章中的示例时,我收到错误:NameError: name 'wckCalendar' is not defined。我在 Windows 32 位机器上运行 Python 3.4.1。任何想法?谢谢。
    • @sedeh 帖子中没有 wckCalendar。检查您的代码。
    • @J.F.Sebastian 没错,我并没有尝试直接调用 wckCalendar。它只是显示在错误消息中。请参阅我的帖子here 讨论该问题。
    • @törzsmókus:如果答案是错误的,那么它的可读性并不重要。
    • @törzsmókus:看看我的回答:它可能会产生 两个 不同的数字。您的答案产生了 一个 数字,但没有提及是哪一个。
    【解决方案6】:

    我使用ciso8601,比 datetime 的 strptime 快 62 倍。

    t = "01/12/2011"
    ts = ciso8601.parse_datetime(t)
    # to get time in seconds:
    time.mktime(ts.timetuple())
    

    您可以了解更多here

    【讨论】:

    • 这是一个绝妙的建议。我刚刚使用它并从执行中节省了大量时间。
    • 天哪,这速度很快
    • 并且 +1 不需要我拼出时间字符串格式是什么。
    【解决方案7】:

    我建议dateutil:

    import dateutil.parser
    dateutil.parser.parse("01/12/2011", dayfirst=True).timestamp()
    

    【讨论】:

    • 错了。 OP 预计时间为"%d/%m/%Y" 格式。比较:dateutil.parser.parse("01/02/2001")datetime.strptime("01/02/2001", "%d/%m/%Y")
    • 感谢@jfs,很好。我相应地更新了我的答案。 (作为非美国人,我不会认为不合逻辑的 M/D/Y 格式是解析器的默认格式。)
    • 除非您的本地时区是 UTC,否则它不会产生预期的 1322697600。见my comment from 2014
    【解决方案8】:

    只需使用 datetime.timestamp(您的 datetime 实例),datetime 实例包含时区信息,因此时间戳将是标准的 utc 时间戳。如果将日期时间转换为时间元组,它将失去它的时区,因此结果将是错误的。 如果你想提供一个接口,你应该这样写: int(datetime.timestamp(time_instance)) * 1000

    【讨论】:

      【解决方案9】:

      很多这些答案都懒得考虑日期一开始就很幼稚

      正确地说,您需要首先将天真日期设为可感知时区的日期时间

      import datetime
      import pytz
      # naive datetime
      d = datetime.datetime.strptime('01/12/2011', '%d/%m/%Y')
      >>> datetime.datetime(2011, 12, 1, 0, 0)
      
      # add proper timezone
      pst = pytz.timezone('America/Los_Angeles')
      d = pst.localize(d)
      >>> datetime.datetime(2011, 12, 1, 0, 0,
      tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)
      
      # convert to UTC timezone
      utc = pytz.UTC
      d = d.astimezone(utc)
      >>> datetime.datetime(2011, 12, 1, 8, 0, tzinfo=<UTC>)
      
      # epoch is the beginning of time in the UTC timestamp world
      epoch = datetime.datetime(1970,1,1,0,0,0,tzinfo=pytz.UTC)
      >>> datetime.datetime(1970, 1, 1, 0, 0, tzinfo=<UTC>)
      
      # get the total second difference
      ts = (d - epoch).total_seconds()
      >>> 1322726400.0
      

      还有:

      小心,在datetime.datetime 中使用pytz 代替tzinfo 对于许多时区都不起作用。见datetime with pytz timezone. Different offset depending on how tzinfo is set

      # Don't do this:
      d = datetime.datetime(2011, 12, 1,0,0,0, tzinfo=pytz.timezone('America/Los_Angeles'))
      >>> datetime.datetime(2011, 1, 12, 0, 0, 
      tzinfo=<DstTzInfo 'America/Los_Angeles' LMT-1 day, 16:07:00 STD>)
      # tzinfo in not PST but LMT here, with a 7min offset !!!
      
      # when converting to UTC:
      d = d.astimezone(pytz.UTC)
      >>> datetime.datetime(2011, 1, 12, 7, 53, tzinfo=<UTC>)
      # you end up with an offset
      

      https://en.wikipedia.org/wiki/Local_mean_time

      【讨论】:

        【解决方案10】:

        似乎效率很高:

        import datetime
        day, month, year = '01/12/2011'.split('/')
        datetime.datetime(int(year), int(month), int(day)).timestamp()
        

        每个循环 1.61 µs ± 120 ns(7 次运行的平均值 ± 标准偏差,每次 100000 次循环)

        【讨论】:

        • datetime 函数是什么? datetime 来自 datetime 库不支持 .timestamp()
        • @Joooeey:It does, on Python 3.3 or later。发布问题时不可用,但自 2012 年 9 月起可用。
        【解决方案11】:

        只需使用datetime.datetime.strptime:

        import datetime
        stime = "01/12/2011"
        print(datetime.datetime.strptime(stime, "%d/%m/%Y").timestamp())
        

        结果:

        1322697600
        

        要使用 UTC 而不是本地时区,请使用 .replace:

        datetime.datetime.strptime(stime, "%d/%m/%Y").replace(tzinfo=datetime.timezone.utc).timestamp()
        

        【讨论】:

        • 对于一个完整的anwser,你必须说它只对python 3.3+有效
        • 在第一个示例中,结果是 float 而不是 int
        【解决方案12】:

        您可以参考以下链接使用datetime.datetime 中的strptime 函数,将日期从任何格式与时区一起转换。

        https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

        【讨论】:

          【解决方案13】:

          获取 UNIX 纪元时间的简单函数。

          注意:此函数假定输入日期时间为 UTC 格式(请参阅此处的comments)。

          def utctimestamp(ts: str, DATETIME_FORMAT: str = "%d/%m/%Y"):
              import datetime, calendar
              ts = datetime.datetime.utcnow() if ts is None else datetime.datetime.strptime(ts, DATETIME_FORMAT)
              return calendar.timegm(ts.utctimetuple())
          

          用法

          >>> utctimestamp("01/12/2011")
          1322697600
          >>> utctimestamp("2011-12-01", "%Y-%m-%d")
          1322697600
          

          【讨论】:

            【解决方案14】:

            你可以转换成isoformat

            my_date = '2020/08/08'
            my_date = my_date.replace('/','-') # just to adapte to your question
            date_timestamp = datetime.datetime.fromisoformat(my_date).timestamp()
            

            【讨论】:

              【解决方案15】:

              我会给初学者(比如我)一个答案:

              你有日期字符串"01/12/2011"。然后可以写成"%d/%m/%Y"的格式。如果您想格式化为另一种格式,例如 "July 9, 2015"here,这是一个很好的备忘单。

              • 导入datetime 库。

              • 使用datetime.datetime 类来处理日期和时间组合。

              • 使用strptime 方法将字符串日期时间转换为对象日期时间。

              • 最后,使用timestamp 方法以浮点数形式获取Unix 纪元时间。所以,

              import datetime
              print( int( datetime.datetime.strptime( "01/12/2011","%d/%m/%Y" ).timestamp() ) )
              
              # prints 1322712000
              

              【讨论】:

                【解决方案16】:

                你可以双向unix epoch &lt;==&gt; datetime

                import datetime
                import time
                
                
                the_date = datetime.datetime.fromtimestamp( 1639763585 )
                
                
                
                unix_time = time.mktime(the_date.timetuple())
                
                assert  ( the_date == datetime.datetime.fromtimestamp(unix_time) ) & \
                        ( time.mktime(the_date.timetuple()) == unix_time         )   
                

                【讨论】:

                  猜你喜欢
                  • 2016-09-15
                  • 1970-01-01
                  • 2014-10-07
                  • 2011-05-05
                  • 1970-01-01
                  • 1970-01-01
                  • 2011-10-23
                  • 2021-07-06
                  • 1970-01-01
                  相关资源
                  最近更新 更多