sylar_80
sylar_80

Reputation: 375

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

the string I have is like this one

abc_8g_1980_312.tif

where 1980_312 are, respectively, YYYY_DDD. The desired output should be 19801107 I'm trying to use the website https://regex101.com/

thanks

Upvotes: 0

Views: 1486

Answers (1)

zwer
zwer

Reputation: 25799

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:

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. 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, e.g.:

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():

str_date = real_date.strftime('%Y%m%d')
# 19801107

Upvotes: 1

Related Questions