简体   繁体   English

将 Shell 日期格式转换为 Python 日期格式

[英]Convert Shell date format to Python date format

Can below piece of shell date format be converted to python date format?下面的shell日期格式可以转换为python日期格式吗?

date_used = $(date --date="$(date +%Y-%m-15) - 1 month" "+%Y_%m")

As per my understanding this above format is just taking day as 15 of current month and it simply subtracts 1 month and results in giving output in the format of year_month.根据我的理解,上述格式只是将当天作为当月的 15 天,它只是减去 1 个月并导致输出格式为 year_month。

Output of the above shell date format -->上述shell日期格式的输出-->

echo $date_used = 2022_05

Can this particular scenario be done using python?可以使用 python 完成这个特定场景吗?

Any update about it would be really appreciable.任何关于它的更新都将是非常可观的。

An equivalent would be:等效的将是:

from datetime import datetime,timedelta

# Current date, replace date with 15, subtract 30 days and format
date_used = (datetime.now().replace(day=15) - timedelta(days=30)).strftime('%Y_%m')
print(date_used)

Output:输出:

2022_05

You can use python's datetime module to do this您可以使用 python 的datetime模块来执行此操作

it has a function named strptime you can use to read date and time data with format code very similar to unix date format (or maybe its even same i'm not sure)它有一个名为strptime的函数,您可以使用与 unix 日期格式非常相似的格式代码读取日期和时间数据(或者我不确定它是否相同)

and strftime to output in a certain format as wellstrftime以某种格式输出

you can see the functions and the format code to see if there's any different on https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes您可以在https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes上查看函数和格式代码以查看是否有任何不同

Example code示例代码

from datetime import datetime, timedelta

date = datetime.strptime((datetime.now() - timedelta(days=30)).strftime("%Y-%m") + "-15", "%Y-%m-%d")
print(date)

print(date.strftime("%Y_%m"))

output输出

2022-05-15 00:00:00
2022_05

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM