Python time integer issue - python

I'm trying to calculate the time difference between a 'then' and 'now'. I've altered the format so that I can compare it better (I dont need seconds or nanoseconds, etc)
the 'then' time comes from an ecryption, and it's being parsed through to compare, which is what gives the error I'm afraid.
def decrypt_and_compare_date():
from Crypto.Cipher import XOR
from datetime import timedelta, datetime, date
import base64
import config
cipher = XOR.new(cryptopassword)
encrypted = cipher.decrypt(base64.b64decode(config.event_date))
then = date(encrypted)
now = date(2015,10,5)
days = (now - then).days
print days + " days ago."
gives me the following error:
TypeError: an integer is required
if I use the * on this line:
then = date(encrypted)
It then parses me this error.
TypeError: function takes at most 3 arguments (8 given)
date(encrypted) should be 2015,7,1
Does anyone know the magic trick?

Try using datetime.strptime() to parse the string as date.
Example -
>>> s = "2015,7,1"
>>> from datetime import datetime
>>> d = datetime.strptime(s,'%Y,%m,%d').date()
>>> d
datetime.date(2015, 7, 1)
This is based on assumption that the second number in the string is month and the third is the date, if its opposite, interchange %m and %d in '%Y,%m,%d' .

Related

"PT" Formatted time string in python

I'm receiving a string which is formatted in the following way: "PTXMYS" Where X is the amount of minutes and Y is the amount of seconds.
I'd like to turn that string into an int which presents the amount of seconds in total.
I tried using datetime and other stuff and it just won't work for me, I read online that this formatting is standard for iso8601 so it's weird for me that it doesn't really work.
String example:
x="PT4M13S"
there is a third-party library that can parse these strings, isodate:
import isodate
isodate.parse_duration("PT4M13S")
# datetime.timedelta(seconds=253)
isodate.parse_duration("PT4M13S").total_seconds()
# 253.0
And for completeness, there is an option to do this with datetime's strptime and timedelta's total_seconds():
from datetime import datetime, timedelta
# parse minute and second to datetime object:
t = datetime.strptime("PT4M13S","PT%MM%SS")
# convert to timedelta to get the total seconds
td = timedelta(minutes=t.minute, seconds=t.second)
td.total_seconds()
# 253
What you are trying to do can easily be solved using regex. Try this out:
import re
m, s = re.findall('PT(\d+)M(\d+)S',x)[0]
total_secs = 60*int(m) + int(s)
print(total_secs)
Output:
253

python: Calculating seconds from a datetime string with extra characters

I want to create a new column which contains seconds since 1970 for each row for the following input file:
timestamp, air_temp, rh, pressure, dir, spd
2016-11-30T00:00:00Z,-36.50,56.00,624.60,269.00,5.80
2016-11-30T01:00:00Z,-35.70,55.80,624.70,265.00,5.90
2016-11-30T02:00:00Z,-34.80,56.00,625.00,266.00,6.30
The first column represents the timestamp but it contains extra characters 'T' and 'Z'. My current code looks like this:
i = 0
ip_file.readline()
for line in ip_file:
line = line.strip()
year[i] = int(line[0:4])
month[i] = int(line[5:7])
day[i] = int(line[8:10])
hour[i] = int(line[11:13])
time[i] = (datetime(year[i],month[i],day[i],hour[i])-datetime(1970, 1, 1)).total_seconds()
i += 1
This returns me what I want but it takes long time if input file is big. If the timestamp didn't had those extra characters, I would have directly used it instead of calculating year, month, day and hour. Is there a better way? Any thoughts would be appreciated.
Instead of using string slice. Why not split the string by comma? And use strptime method in datetime module to convert string datetime to datetime object.
Example:
import datetime
with open(path, "r") as infile:
for i in infile.readlines()[1:]:
dVal = i.strip().split(",")[0]
print (datetime.datetime.strptime(dVal, '%Y-%m-%dT%H:%M:%SZ')-datetime.datetime(1970, 1, 1)).total_seconds()
Output:
1480464000.0
1480467600.0
1480471200.0
Input:
import datetime as dt
line = '2016-11-30T00:00:00Z,-36.50,56.00,624.60,269.00,5.80'
# We know the datetime data is always 20 characters long
line_dt_str = line[:20]
line_secs_since_epoch = dt.datetime.strptime(line_dt_str, '%Y-%m-%dT%H:%M:%SZ').timestamp()
print(line_secs_since_epoch)
Output:
1480482000.0
Note that there is a difference between calling .timestamp() and subtracting your datetime from the 1970 epoch. This comes from how these two methods handle (or don't handle) daylight savings time. Read more here
You can achieve this by first splitting your line in file on , and casting it to datetime object
>>> import datetime
>>> line = '2016-11-30T00:00:00Z,-36.50,56.00,624.60,269.00,5.80'
>>> t = datetime.strptime(line.split(',')[0], '%Y-%m-%dT%H:%M:%SZ')
To convert to seconds you can simply use:
>>> int(t.strftime("%s"))
>>> 1480435200

Two-Digit dates in Python

I am trying to print the date and month as 2 digit numbers.
timestamp = date.today()
difference = timestamp - datetime.timedelta(localkeydays)
localexpiry = '%s%s%s' % (difference.year, difference.month, difference.day)
print localexpiry
This gives the output as 201387. This there anyway to get the output as 20130807. This is because I am comparing this against a string of a similar format.
Use date formatting with date.strftime():
difference.strftime('%Y%m%d')
Demo:
>>> from datetime import date
>>> difference = date.today()
>>> difference.strftime('%Y%m%d')
'20130807'
You can do the same with the separate integer components of the date object, but you need to use the right string formatting parameters; to format an integer to two digits with leading zeros, use %02d, for example:
localexpiry = '%04d%02d%02d' % (difference.year, difference.month, difference.day)
but using date.strftime() is more efficient.
You can also use format (datetime, date have __format__ method):
>>> import datetime
>>> dt = datetime.date.today()
>>> '{:%Y%m%d}'.format(dt)
'20130807'
>>> format(dt, '%Y%m%d')
'20130807'
two digit month, day and four digit year in django like this 04/14/2019: {{text1.pub_date|date:"m/d/Y"}}

Slicing and Replacing Unicode String Characters

I have the following loop I'm trying to use to replace characters in a unicode string. The data I'm getting for this loop is in the following format: YYYY-MM-DD HH:MM:SS
This data is apparently stored in UTC, so when I grab it and append these times & dates to my list appts_list its 4 hours ahead.
I've gotten as far as slicing the unicode string and doing the math on these characters and getting what would be the correct hour I need, but I'm having a problem getting that back into a string so I can write it to my list appts_list.
I'm getting TypeError when I try to write the integer for the correct hour time_slice_int back into the original string. I decided to try to put the entire string into a list and change them there, but that isn't working either.
Ideally I want an appointment for '2013-06-28 15:30:00' to be entered into my appts_list as '2013-06-28 11:30:00'.
The print statements are there for me to debug as I ran it. They are not necessary for the final version.
Anyone have any suggestions or solutions?
for appt in todays_appts:
time = appt['apptdateourtime_c']
time_slice = time[11:13]
time_slice_int = int(time_slice)
time_slice_int -= 4
print(time_slice_int)
appt_time = list(time)
print(appt_time)
print(appt_time[11:13])
#appt_time[11:13] = time_slice_int
#appts_list.append()
print('AppointmentScheduled')
#print(appt['apptdateourtime_c'])
#print(time)
print('')
You should use the datetime module here:
>>> from datetime import datetime, timedelta
>>> strs = '2013-06-28 15:30:00'
>>> d = datetime.strptime(strs, "%Y-%m-%d %H:%M:%S")
datetime.strptime returns a datetime object:
>>> d
datetime.datetime(2013, 6, 28, 15, 30)
>>> d.hour
15
>>> d.month
6
Now decrease 4 hours from the above datetime object(d) using timedelta and assign the new object to a variable:
>>> d1 = d - timedelta(hours = 4)
Now use datetime.strftime to get a string of required format:
>>> datetime.strftime(d1,"%Y-%m-%d %H:%M:%S")
'2013-06-28 11:30:00'

How to convert integer into date object python?

I am creating a module in python, in which I am receiving the date in integer format like 20120213, which signifies the 13th of Feb, 2012. Now, I want to convert this integer formatted date into a python date object.
Also, if there is any means by which I can subtract/add the number of days in such integer formatted date to receive the date value in same format? like subtracting 30 days from 20120213 and receive answer as 20120114?
This question is already answered, but for the benefit of others looking at this question I'd like to add the following suggestion: Instead of doing the slicing yourself as suggested in the accepted answer, you might also use strptime() which is (IMHO) easier to read and perhaps the preferred way to do this conversion.
import datetime
s = "20120213"
s_datetime = datetime.datetime.strptime(s, '%Y%m%d')
I would suggest the following simple approach for conversion:
from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))
For adding/subtracting an arbitary amount of days (seconds work too btw.), you could do the following:
date += timedelta(days=10)
date -= timedelta(days=5)
And convert back using:
s = date.strftime("%Y%m%d")
To convert the integer to a string safely, use:
s = "{0:-08d}".format(i)
This ensures that your string is eight charecters long and left-padded with zeroes, even if the year is smaller than 1000 (negative years could become funny though).
Further reference: datetime objects, timedelta objects
Here is what I believe answers the question (Python 3, with type hints):
from datetime import date
def int2date(argdate: int) -> date:
"""
If you have date as an integer, use this method to obtain a datetime.date object.
Parameters
----------
argdate : int
Date as a regular integer value (example: 20160618)
Returns
-------
dateandtime.date
A date object which corresponds to the given value `argdate`.
"""
year = int(argdate / 10000)
month = int((argdate % 10000) / 100)
day = int(argdate % 100)
return date(year, month, day)
print(int2date(20160618))
The code above produces the expected 2016-06-18.
import datetime
timestamp = datetime.datetime.fromtimestamp(1500000000)
print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))
This will give the output:
2017-07-14 08:10:00

Categories

Resources