1

我有一个脚本,我只需要以2015-07-28最后一次 git 提交的格式检索日期。

但是git log -1 --pretty=format:"%ci"如果我想在终端中使用,Tue Jul 28 16:23:24 2015 +0530那么如果我想

将此作为字符串传递给subprocess.Popen喜欢

subprocess.Popen('git log -1 --pretty=format:"%cd"' shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE))

但这会给我带来错误TypeError: %c requires int or char,我猜我们正在将 char 传递给 %c 的 python 东西,而那是为了使用 git 命令获取日期。

我需要将此日期连接到我的 python 脚本中的字符串。

4

2 回答 2

1

代码不见了,,还有一个额外的)

proc = subprocess.Popen(
    'git log -1 --pretty=format:"%cd"',
    shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = proc.stdout.read()
proc.wait()

获取命令输出后,您可以使用datetime.datetime.strptime将字符串转换为datetime对象,并将其转换为您喜欢的格式datetime.datetime.strftime

import datetime
dt = datetime.datetime.strptime(output.rsplit(None, 1)[0], '%a %b %d %H:%M:%S %Y')
print(output)
print(dt.strftime('%Y-%m-%d'))
于 2015-08-01T12:28:24.487 回答
1

错误消息与您的代码不对应:有问题的代码将产生SyntaxError,而不是TypeError

你不需要shell=True。要获取 git 的输出,您可以使用subprocess.check_output()函数

from subprocess import check_output

date_string = check_output('git log -1 --pretty=format:"%ci"'.split()).decode()
于 2015-08-01T15:49:58.847 回答