在Python中将字符串日期转换为时间戳

时间:2012-03-09 16:47:56

标签: python datetime

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

"01/12/2011" -> 1322697600

14 个答案:

答案 0 :(得分:259)

>>> import time
>>> import datetime
>>> s = "01/12/2011"
>>> time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple())
1322697600.0

答案 1 :(得分:35)

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

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的午夜和当地时间是同一时间实例。

答案 2 :(得分:32)

我使用ciso8601,比日期时间快了62倍。

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

您可以了解更多here

答案 3 :(得分:27)

>>> int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime("%s"))
1322683200

答案 4 :(得分:20)

答案还取决于您输入的日期时区。如果您的日期是本地日期,那么您可以使用像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

答案 5 :(得分:8)

只需使用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()

答案 6 :(得分:6)

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

然后从那里使用mktime来获得你的浮动。

答案 7 :(得分:5)

我建议dateutil

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

答案 8 :(得分:4)

很多这些答案都没有考虑到

开头的日期是天真的

说实话,您需要先将天真日期设为时区感知日期时间

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

同时

请注意,pytz tzinfo datetime.datetime # 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 对多个时区不起作用。见datetime with pytz timezone. Different offset depending on how tzinfo is set

@objc

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

答案 9 :(得分:1)

您可以转换为同格式

locals {
  create_me = terraform.workspace == "dev" ? 0 : 1
}

resource "aws_acm_certificate" "default" {
  count = local.create_me
  domain_name = "www.test.uk"
  validation_method = "DNS"
}

resource "aws_route53_record" "validation" {
  count = local.create_me
  name = aws_acm_certificate.default.domain_validation_options[count.index].resource_record_name
  type = aws_acm_certificate.default.domain_validation_options[count.index].resource_record_type
  zone_id = "Z0725470IF9R8J77LPTU"
  records = [
    aws_acm_certificate.default.domain_validation_options[count.index].resource_record_value]
  ttl = "60"
}

resource "aws_acm_certificate_validation" "default" {
  count = local.create_me
  certificate_arn = aws_acm_certificate.default[count.index].arn
  validation_record_fqdns = [
    aws_route53_record.validation[count.index].fqdn,
  ]
}

答案 10 :(得分:0)

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

答案 11 :(得分:0)

似乎效率很高:

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次循环)

答案 12 :(得分:0)

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

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

答案 13 :(得分:0)

获取utctime的简单函数。

r = requests.post('https://api.socialtables.com/4.0/guestlists/965d8450-daf3- 
11e9-9e6a-1fbad5325279/guests', data={ 
"id":"1231231231","first_name":"fname","last_name":"lname","email":"aa@aaa.aa" 
})