darkhorse
darkhorse

Reputation: 8722

What is an ideal regex pattern for a timestamp with a timezone?

I am trying to store timestamps with timezones, and I need a regex pattern to do it properly. The format is illustrated using the examples below:

2014-12-01 17:15:52
2014-12-01 17:15:52.213121
2014-12-01 17:15:52 Africa/Cairo
2014-12-01 17:15:52.213121 Africa/Cairo

All are valid timestamps. In other words, the precision of microseconds is optional, and so is the timezone. The timezone can be regarded as a string. So far, I have the following pattern:

r'^\d\d\d\d-(0?[1-9]|1[0-2])-(0?[1-9]|[12][0-9]|3[01]) (00|[0-9]|1[0-9]|2[0-3]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])*$'

This is good for only storing the required part, that is, without the microseconds precision, and the timezone. I am kinda lost on how to approach this.

Should I use | and have all the patterns there, one with the microseconds without timezone, one with timezone without microseconds, one without both, one with both?

Thanks for any help.

Note: Because someone is inevitably going to bring this up, I fully understand a regex pattern alone cannot validate a datetime. I intend to use this pattern to split the string off, and validate each of those parts to make sure the timestamp is valid or not. So please, no comments or answers mentioning that detail.

Upvotes: 0

Views: 1325

Answers (1)

The fourth bird
The fourth bird

Reputation: 163362

You could update your regex by adding 2 optional non capturing groups at the end of your regex to match a dot and 1+ digits like .213121 and match a pattern with a forward slash like Africa/Cairo using \S to match any non whitespace character.

If \S is too broad of a match, you could specify a character class listing all the allowed characters.

(?:\.\d+)?(?: \S+\/\S+)?$

See the updated regex

Note that this group ([0-9]|[0-5][0-9])* does not need a quantifier, so you could omit the *

If what comes before and after the forward slash can also contain whitespaces you could also use:

(?:\.\d+)?(?: [^\r\n\/]+\/[^\r\n\/]+)?

Upvotes: 1

Related Questions