Change the format of a QDate - python

I need to change the format of a QDate. Here is my code:
yday = (QtCore.QDate.currentDate().addDays(-1))
And I got this result...
PyQt4.QtCore.QDate(2015, 4, 2)
But I need the date in this format:
2015/04/03

A QDate can be converted to a string using its toString method:
>>> yday = QtCore.QDate.currentDate().addDays(-1)
>>> yday.toString()
'Thu Apr 2 2015'
>>> yday.toString(QtCore.Qt.ISODate)
'2015-04-02'
>>> yday.toString('yyyy/MM/dd')
'2015/04/02'
Note that this output is from Python3. If you're using Python2, by default, the output will be a QString - but it can be converted to a python string using unicode().

you can use datetime.strftime()
yourdate.strftime('%Y, %m, %d')

Related

Convert Date and Time in required format "Jun 9 18:04:42:"

Current Format is Jun 9 18:04:42:
Required Format is 09/06/2021 18:04:42:00
There is no year in current format, but I need to add it.
I have tried following code
s= 'Jun 9 18:04:42:'
'''
def convert_to_date(s):
if s!='None':
if s=='':
return s
else:
print ("to unpack values:",s)
s=s.replace(' ', ':')
f_month,f_day,f_hour,f_minute,f_seconds,f_miliseconds = s.split(':')
s = str(f_month) +'-' + str(f_day) + ' ' + str(f_hour) + ':' + str(f_minute)+':'+str(f_seconds) +':'+str(f_miliseconds)
print ("unpacked values:",s)
return s
'''
output is: 'Jun-9 18:04:42:'
Use dateutil module's parser.parse method, which can parse a range of differently formatted date strings and return a datetime.datetime object. Then you can convert it to any other format using strftime function:
>>> from dateutil.parser import parse
>>> dt = parse('Jun 9 18:04:42').strftime('%d/%m/%Y %H:%M:%S:00')
>>> print (dt)
09/06/2021 18:04:42:00

Time data does not match format '%c'

This is very unexpected behavior...
I create a time string using the '%c' directive.
%c is the Locale’s appropriate date and time representation.
Then I try to parse the resulting time string, specifying the same '%c' as the string's format.
However this does not work as you can see from the error below. What am I missing?
I need to be able to store the time in a human-readable localized string, and then convert the string back into a struct_time so I can extract information from it.
(It is extremely important that the string be localized, and I of course don't want to write parsing algorithms for all locales around the world!)
# Ensure the locale is set.
import locale
locale.setlocale(locale.LC_ALL, '')
'en_US.UTF-8'
# 1. Create a localized time string using the '%c' directive.
import datetime
time_stamp = datetime.datetime.now().strftime('%c')
time_stamp
'Mon 21 Dec 2020 03:47:55 PM '
# 2. Try to parse the string using the same directive used to create it.
import time
time.strptime(time_stamp, '%c')
# 3. Unexpected error...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.8/_strptime.py", line 562, in _strptime_time
tt = _strptime(data_string, format)[0]
File "/usr/lib/python3.8/_strptime.py", line 349, in _strptime
raise ValueError("time data %r does not match format %r" %
ValueError: time data 'Mon 21 Dec 2020 03:47:55 PM ' does not match format '%c'
Your locale is probably not configuring .strftime("%c") the way you expect and .strptime is objecting to the postfixed %p (PM)
Use locale.nl_langinfo(locale.D_T_FMT) to build your format instead!
>>> locale.nl_langinfo(locale.D_T_FMT)
'%a %b %e %H:%M:%S %Y'
>>> locale.setlocale(locale.LC_ALL, '')
'en_US.UTF-8'
>>> locale.nl_langinfo(locale.D_T_FMT)
'%a %b %e %X %Y'
However, if you
.. know the exact structure of the output, filter exact matches with a regex and then parse
.. can control the format, don't bother to format it and directly use time.time()
.. or always work in UTC and format as ISO 8601, deriving a tz-aware object and reading back with a custom parser (refer to the Caution on .fromisoformat)
>>> datetime.datetime.now(tz=datetime.timezone.utc)
datetime.datetime(2020, 12, 22, 0, 4, 29, 537007, tzinfo=datetime.timezone.utc)
use pytz, which is much "smarter" than the datetime builtin lib and properly supports a huge variety of locales
Instead of using %c, you can specify how you want to format the date using %a, %b and other directives. For example:
import locale
locale.setlocale(locale.LC_ALL, 'en_US.utf-8')
import datetime
fmt = '%a %b %d %Y %H:%M:%S'
time_stamp = datetime.datetime.now().strftime(fmt)
print(time_stamp)
import time
print(time.strptime(time_stamp, fmt))
This produces an output that you are looking for:
Output:
Mon Dec 21 2020 21:27:50
time.struct_time(tm_year=2020, tm_mon=12, tm_mday=21, tm_hour=21, tm_min=27, tm_sec=50, tm_wday=0, tm_yday=356, tm_isdst=-1)

How to translate datetime string to sql format?

Is there any shorter method to translate this ISO 8601 compatible UTC time to the SQL DATETIME format?
>>> str = "2016-03-28T20:23:46+0800"
>>> temp = str.split('T')
>>> temp[1] = temp[1].rstrip('+')
>>> temp[1]
'20:23:46+0800'
>>> temp[1] = temp[1].split('+')[0]
>>> result = " ".join(temp)
>>> result
'2016-03-28 20:23:46'
Thanks!
You can simply switch formats:
>>> date_str = "2016-03-28T20:23:46+0800"
>>> format = '%Y-%m-%dT%H:%M:%S%z'
>>> new_format = '%Y-%m-%d %H:%M:%S'
>>> datetime.datetime.strptime(date_str, format).strftime(new_format)
'2016-03-28 20:23:46'
This will not work in python 2.x as it does not support the %z flag. See timezone python 2 support for a workaround
There is no easy way to do this.
Checkout this post for more details on possible solutions.
If you're looking for a quick hack try this:
st = '2016-03-28T20:23:46+0800'
st[:19].replace("T", " ")
Or, if you need the date in datetime:
datetime.datetime.strptime(st[:19], '%Y-%m-%dT%H:%M:%S')

Python: Parse one string into multiple variables?

I am pretty sure that there is a function for this, but I been searching for a while, so decided to simply ask SO instead.
I am writing a Python script that parses and analyzes text messages from an input file. Each line looks like this:
Oct 24, 2014, 19:20 - Lee White: Hello world!
or:
Apr 4, 19:20 - Lee White: Hello world!
If the year in the datetime is not mentioned, it means that the message was sent in the current year.
What I want to do, is parse this string into multiple variables. Ideally, I am looking for a function that takes an input string, a format string, and a couple of variables to store the output in:
foo(input, "MMM DD, YYYY, HH:MM - Sender: Text", &mon, &day, &year, &hour, &minutes, &sender, &text)
Does such a thing exist in Python?
This uses the remarkably useful dateutil library to make date parsing easier - you can pip install python-dateutil or easy_install python-dateutil it. Split the data on the : and the - to get message and sender, then process the date text to get a datetime object where you can access its various attributes to get the components required, eg:
from dateutil.parser import parse
s = 'Apr 4, 19:20 - Lee White: Hello world!'
fst, _, msg = s.rpartition(': ')
date, _, name = fst.partition(' - ')
date = parse(date)
name, msg, date.year, date.month, date.day, date.hour, date.minute
# ('Lee White', 'Hello world!', 2015, 4, 4, 19, 20)
Method strptime() may be used:
import time
strn = 'Apr 4, 19:20 - Lee White: Hello world!'
try:
date = time.strptime(strn.split(' - ')[0],'%b %d, %Y, %H:%M')
year = date.tm_year
except ValueError:
date = time.strptime(strn.split(' - ')[0],'%b %d, %H:%M')
year = time.asctime().split()[-1]
sender = strn.split('- ')[1].split(':')[0]
text = strn.split(': ')[1]
date.tm_mon, date.tm_mday, year, date.tm_hour, date.tm_min, sender, text

How get a datetime string to suffix my filenames?

I need a function to generate datafile names with a suffix which must be the current date and time.
I want for the date Feb, 18 2014 15:02 something like this:
data_201402181502.txt
But this is that I get: data_2014218152.txt
My code...
import time
prefix_file = 'data'
tempus = time.localtime(time.time())
suffix = str(tempus.tm_year)+str(tempus.tm_mon)+str(tempus.tm_mday)+
str(tempus.tm_hour)+str(tempus.tm_min)
name_file = prefix_file + '_' + suffix + '.txt'
You can use time.strftime for this, which handles padding leading zeros e.g. on the month:
from time import strftime
name_file = "{0}_{1}.txt".format(prefix_file,
strftime("%Y%m%d%H%M"))
If you simply turn an integer to a string using str, it will not have the leading zero: str(2) == '2'. You can, however, specify this using the str.format syntax: "{0:02d}".format(2) == '02'.
Looks like you want
date.strftime(format)
The format string will allow you to control the output of strftime, try something like:
"%b-%d-%y"
From http://docs.python.org/2/library/datetime.html
Using str.format with datetime.datetime object:
>>> import datetime
>>> '{}_{:%Y%m%d%H%M}.txt'.format('filename', datetime.datetime.now())
'filename_201402182313.txt'

Categories