[英]Convert julian date to YYYYMMDD using python datetime with regex
is there a way to convert using python datetime with regex a julian date into a calendar one with the following format: YYYYMMDD有没有办法使用 python 日期时间和正则表达式朱利安日期转换为具有以下格式的日历:YYYYMMDD
the string I have is like this one我的弦是这样的
abc_8g_1980_312.tif abc_8g_1980_312.tif
where 1980_312 are, respectively, YYYY_DDD.其中 1980_312 分别是 YYYY_DDD。 The desired output should be 19801107 I'm trying to use the website https://regex101.com/
所需的 output 应该是 19801107 我正在尝试使用网站https://regex101.com/
thanks谢谢
Regex is the wrong tool for the job when it comes to converting dates, you can still use it to extract the 'interesting' part of your string ( YYYY_DDD
from the image name), tho:在转换日期时,正则表达式是错误的工作工具,您仍然可以使用它来提取字符串的“有趣”部分(图像名称中的
YYYY_DDD
),但:
import re
filename = 'abc_8g_1980_312.tif'
date_str = re.search(r'\d{4}_\d+', filename).group() # '1980_312'
Of course, if there are more patterns that might occur, I'd advise making the pattern more strict, for example you can put the above regex in a group and then match \.tif$
after it to ensure it always searches for the pattern at the end of tif
filenames.当然,如果可能出现更多的模式,我建议让模式更严格,例如你可以将上面的正则表达式放在一个组中,然后在它之后匹配
\.tif$
以确保它总是搜索模式在tif
文件名的末尾。 If it's always this format, you can completely forgo regex and just split / partition your string to extract the 'important' part but I'll leave that as an exercise for you;)如果它总是这种格式,您可以完全放弃正则表达式,只需拆分/分区您的字符串以提取“重要”部分,但我将把它留给您作为练习;)
Once you get the YYYY_DDD
part from the filename, you can use datetime.datetime.strptime()
to get to the actual date, eg:从文件名中获取
YYYY_DDD
部分后,您可以使用datetime.datetime.strptime()
获取实际日期,例如:
import datetime
real_date = datetime.datetime.strptime(date_str, '%Y_%j')
# datetime.datetime(1980, 11, 7, 0, 0)
Finally, to get to your desired output you can use datetime.datetime.strftime()
:最后,要获得您想要的 output 您可以使用
datetime.datetime.strftime()
:
str_date = real_date.strftime('%Y%m%d')
# 19801107
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.