用Python切片两个日期时间对象

huangapple go评论86阅读模式
英文:

Slice two datetime objects with Python

问题

我有两个 Python 2.7 中的日期时间对象。

第一个看起来像这样:

2018-09-22 00:00:00

而第二个看起来像这样:

1899-12-30 17:20:59

我想要的是从第一个日期时间对象获取日期,从第二个日期时间对象获取时间。

2018-09-22 17:20:59

不幸的是,我在编写一些古老的 GIS 软件,被迫使用 2.7 版本。感谢任何帮助。

英文:

I have two date time objects in Python 2.7.

The first looks like this:

2018-09-22 00:00:00

and the second looks like this:

1899-12-30 17:20:59

I would like to end up with the dates from the first datetime object and the time from the second datetime object.

2018-09-22 17:20:59

Unfortunately I am coding for some old GIS software and compelled to use 2.7
Any help is appreciated.

答案1

得分: 1

请看datetime.datetime.replace()datetime.datetime.combine()方法:

>>> from datetime import datetime
>>> dt1 = datetime.strptime('2018-09-22 00:00:00', '%Y-%m-%d %H:%M:%S')
>>> dt2 = datetime.strptime('1899-12-30 17:20:59', '%Y-%m-%d %H:%M:%S')
>>> dt3 = dt1.replace(hour=dt2.hour, minute=dt2.minute, second=dt2.second)
>>> dt3
datetime.datetime(2018, 9, 22, 17, 20, 59)

# 或者更好的方法
>>> dt4 = datetime.combine(dt1.date(), dt2.time())
>>> dt4
datetime.datetime(2018, 9, 22, 17, 20, 59)
英文:

Have a look at datetime.datetime.replace() and datetime.datetime.combine() methods:

>>> from datetime import datetime
>>> dt1 = datetime.strptime('2018-09-22 00:00:00', '%Y-%m-%d %H:%M:%S')
>>> dt2 = datetime.strptime('1899-12-30 17:20:59', '%Y-%m-%d %H:%M:%S')
>>> dt3 = dt1.replace(hour=dt2.hour, minute=dt2.minute, second=dt2.second)
>>> dt3
datetime.datetime(2018, 9, 22, 17, 20, 59)

# or even better
>>> dt4=datetime.combine(dt1.date(), dt2.time())
>>> dt4
datetime.datetime(2018, 9, 22, 17, 20, 59)

答案2

得分: 0

如果这两个时间戳都是datetime对象,您可以像这样解析它们的部分:

import datetime as dt

fmt = '%Y-%d-%m %H:%M:%S'

one = dt.datetime.strptime('2018-09-22 00:00:00', fmt)
two = dt.datetime.strptime('1899-12-30 17:20:59', fmt)

# 从第一个时间戳获取日期
# 从第二个时间戳获取时间
# 使用这些信息创建一个新的datetime对象
new_timestamp = dt.datetime.combine(one.date(), two.time())

print(new_timestamp)
# => 2018-09-22 17:20:59
英文:

If both of these timestamps are datetime objects, you should be able to parse out portions of them like so

import datetime as dt


fmt = '%Y-%d-%m %H:%M:%S'

one = dt.datetime.strptime('2018-09-22 00:00:00', fmt)
two = dt.datetime.strptime('1899-12-30 17:20:59', fmt)

# get the 'date' from the first timestamp
# get the 'time' from the second timestamp
# create a new datetime object with this info
new_timestamp = dt.datetime.combine(one.date(), two.time())

print(new_timestamp)
# => 2018-09-22 17:20:59

huangapple
  • 本文由 发表于 2023年6月1日 02:59:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76376535.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定