Ensure filename is in datetime correct format - regex

I want all my files to be off format: 2013-03-31_142436.jpg
i.e. %Y-%m-%d_%H%M%S
I have a script to rename that way but would like to check if the filename is of the format first. I do:
for filename in files:
# check filename not already in file format
filename_without_ext = os.path.splitext(filename)[0];
How do I check filename_without_ext is of format %Y-%m-%d_%H%M%S

Use re:
import re
if re.match(r'\d{4}-\d{2}-\d{2}_\d{6}$', filename_without_ext):
pass # of the right format
This will just check it looks like it has a chance of being a valid date. Use Martijn's answer if you require it to be a valid date.

Just try to parse it as a timestamp:
from time import strptime
try:
strptime(filename_without_ext, '%Y-%m-%d_%H%M%S')
except ValueError:
# Not a valid timestamp
The strptime() test has the advantage that it guarantees that you have a valid datetime value, not just a pattern of digits that still could represent an invalid datetime ('1234-56-78_987654' is not a valid timestamp, for example).

Related

How do I parse a String to Time in Crystal Lang?

I have a String in MM-DD-YYYY format such as: 04-08-2022.
I want to parse that to a Time type.
How do I do that in Crystal?
Crystal has a Time.parse (documentation link) method which can be used in this scenario.
The method receives a String argument to parse along with a String pattern argument and the requested Location of the time. Here is the method signature below.
def self.parse(time : String, pattern : String, location : Location) : Time
For your example, we could use the formatter to provide our custom format as %m-%d-%Y, where %m means month MM format, %d means day DD format, and %Y means YYYY format. Finally we use the local Location of the script being run.
For example:
time = Time.parse("04-08-2022", "%m-%d-%Y", Time::Location.local)

String to YYYY-MM-DD date format in Athena

So I've looked through documentation and previous answers on here, but can't seem to figure this out.
I have a STRING that represents a date. A normal output looks as such:
2018-09-19 17:47:12
If I do this, I get it to return in this format 2018-09-19 17:47:12.000:
SELECT
date_parse(click_time,'%Y-%m-%d %H:%i:%s') click_time
FROM
table.abc
But that's not the output I need. I was just trying to show that I'm close, but clearly missing something. When I change click_time to date_parse(click_time,'%Y-%m-%d'), it sends back INVALID_FUNCTION_ARGUMENT: Invalid format: "2018-09-19 17:47:12" is malformed at " 17:47:12"
So there's clearly something I'm not doing correctly to get it to simply return 2018-09-19.
date_parse converts a string to a timestamp. As per the documentation, date_parse does this:
date_parse(string, format) → timestamp
It parses a string to a timestamp using the supplied format.
So for your use case, you need to do the following:
cast(date_parse(click_time,'%Y-%m-%d %H:%i:%s')) as date )
For your further reference, you can go to the below link for prestodb online documentation https://prestodb.github.io/docs/current/functions/datetime.html

python insert to postgres over psycopg2 unicode characters

Hi guys I am having a problem with inserting utf-8 unicode character to my database.
The unicode that I get from my form is u'AJDUK MARKO\u010d'. Next step is to decode it to utf-8. value.encode('utf-8') then I get a string 'AJDUK MARKO\xc4\x8d'.
When I try to update the database, works the same for insert btw.
cur.execute( "UPDATE res_partner set %s = '%s' where id = %s;"%(columns, value, remote_partner_id))
The value gets inserted or updated to the database but the problem is it is exactly in the same format as AJDUK MARKO\xc4\x8d and of course I want AJDUK MARKOČ. Database has utf-8 encoding so it is not that.
What am I doing wrong? Surprisingly couldn't really find anything useful on the forums.
\xc4\x8d is the UTF-8 encoding representation of Č. It looks like the insert has worked but you're not printing the result correctly, probably by printing the whole row as a list. I.e.
>>> print "Č"
"Č"
>>> print ["Č"] # a list with one string
['\xc4\x8c']
We need to see more code to validate (It's always a good idea to give as much reproducible code as possible).
You could decode the result (result.decode("utf-8")) but you should avoid manually encoding or decoding. Psycopg2 already allows you send Unicodes, so you can do the following without encoding first:
cur.execute( u"UPDATE res_partner set %s = '%s' where id = %s;" % (columns, value, remote_partner_id))
- note the leading u
Psycopg2 can return Unicodes too by having strings automatically decoded:
import psycopg2
import psycopg2.extensions
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)
Edit:
SQL values should be passed as an argument to .execute(). See the big red box at: http://initd.org/psycopg/docs/usage.html#the-problem-with-the-query-parameters
Instead
E.g.
# Replace the columns field first.
# Strictly we should use http://initd.org/psycopg/docs/sql.html#module-psycopg2.sql
sql = u"UPDATE res_partner set {} = %s where id = %s;".format(columns)
cur.execute(sql, (value, remote_partner_id))

I need to remove the date

I need to enter regex into a field which ONLY identifies a varying date.
All files use the same format of: name.y%.m%.d%.blahblahblah
This is an example of what the filename would look like:
LordOfTheRings.14.6.28.The.Twin.Towers
Let's say we have a file called x.
f=open(x,'r')
data=f.read()
import re
y=re.sub(r".\d{2,4}.\d{1,2}.\d{1,2}."," - ",x)
new=open(y,'w')
new.write(data)
After all delete the old file.

QDateTime::fromString returns invalid Date, what am I missing?

I have some code that reads a datetime from a sqlite database, the datetime is returned as a string. when I try to convert it to a date using QDateTime::FromString it returns an invalid date. Below is the time as returned from the database and conversion.
Why is this failing to parse?
// -this is the value returned from the DB currentServerTime=2012-01-17 19:20:27.0
QString format("yyyy/MM/dd hh:mm:ss");
QString qCurrentServerTime(currentServerTime);
now = QDateTime::fromString(qCurrentServerTime, format);
No expert in QT, but if QDateTime::fromString() works as one would (reasonably) expect and according to this, you're not using the correct pattern.
You indicate the string read from the sqllite database is like "2012-01-17 19:20:27.0", then your format should be like yyyy-MM-dd HH:mm:ss.z.
In detail:
Your separator should by '-' not '/' (as you show in the example)
The time seems to be in 24 hours format (19 -> 7 p.m.) (so use HH instead of hh)
You have one digit for milliseconds, so add .z.