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'
Related
I'm trying to convert the list of str to the list of timestamps, then want to create the list of time delta of timestamps using total_seconds()
from datetime import datetime
a = ['091122333','092222222','093333333']
for i in a:
datetime.strptime(str(i),'%H:%M:%S.%f')
print(a)
It shows the error code of time data '091122333' does not match format '%H:%M:%S.%f'
I want to make timestamp 09(%H)11(%M)22(%S)333(%F) if possible.
Could you give me the advice above?
Thank you very much...
You have to first change the representation ( You have : which is not present in list of string in a) and how You manage what is returned from datetime.strptime (You have to store the value while You iterate through list) like that:
from datetime import datetime
a = ['091122333','092222222','093333333']
for t in range(len(a)):
a[t] = datetime.strptime(a[t],'%H%M%S%f')
delta = a[1]-a[0]
print(delta.total_seconds())
The format passed to strptime should represent the format used in the string (there are no colons in your string):
from datetime import datetime
a = ['091122333', '092222222', '093333333']
for i in a:
dt = datetime.strptime(str(i), '%H%M%S%f')
print(dt)
Out:
1900-01-01 09:11:22.333000
1900-01-01 09:22:22.222000
1900-01-01 09:33:33.333000
a project I'm building takes different time lengths from album tracklists in as strings, and I want to add them up cumulatively. The inputs can vary in unpredictability, such as the following list of input time strings:
inputs = ['0:32', '3:19', '11:22']
So I would want to add all these times up like so:
0:32 + 3:19 + 11:22 = = 15:13
I need to make sure the resulting time is a valid timestamp, so incrementing the second/minute/hours realistically is necessary
I figured the best way to do this would be to convert each string time to a python datetime object, but I'm having trouble thinking of how to do this realistically, since all my knowledge and examples I can find of converting a string to a datetime use hard-coded datetime templates, such as:
datetime_str = '09/19/18 13:55:26'
datetime_object = datetime.strptime(datetime_str, '%m/%d/%y %H:%M:%S')
I need to identify multiple different possible string-times, such as :
0:32 = %m:%S
23:19 = %M:%S
01:22:23 = %H:%M:%S
01:2:23 = %H:%m:%S
is there a way to automate this process of adding up multiple different timestamps? My thought process was take the time-string, convert to datetime, convert that datetimeObject to seconds, add them up, then convert it back to dateTime HH:MM:SS format. But I'm getting hung up on how many different possible time inputs I can receive. Any advice is much appreciated as to how I can solve this problem
If you know that they all follow this format, it should be doable to parse manually:
def add_times(inputs):
total_secs=0
for input in inputs:
chunks = map(int, reversed(input.split(':')))
total_secs += sum(chunk*60**i for i,chunk in enumerate(chunks))
return "{}:{}:{}".format(total_secs//3600, (total_secs%3600)//60, total_secs%60)
print(add_times( ['0:32', '3:19', '11:22']))
gives me 0:15:13.
For durations, please work with datetime.timedelta. Here’s how to parse your strings into a timedelta, illustrated step by step:
>>> '5:13'.split(':')
['5', '13']
>>> list(map(int, '5:13'.split(':')))
[5, 13]
>>> list(zip(('seconds', 'minutes', 'hours'), map(int, reversed('5:13'.split(':')))))
[('seconds', 13), ('minutes', 5)]
>>> dict(zip(('seconds', 'minutes', 'hours'), map(int, reversed('5:13'.split(':')))))
{'seconds': 13, 'minutes': 5}
>>> timedelta(**dict(zip(('seconds', 'minutes', 'hours'), map(int, reversed('5:13'.split(':'))))))
datetime.timedelta(seconds=313)
Then add up your timedeltas:
from datetime import timedelta
from functools import reduce
from operator import add
def to_timedelta(duration: str) -> timedelta:
return timedelta(**dict(zip(('seconds', 'minutes', 'hours'), map(int, reversed(duration.split(':'))))))
inputs = ['0:32', '3:19', '11:22']
print(reduce(add, map(to_timedelta, inputs)))
# 0:15:13
A timedelta automatically formats in a nice "H:M:S" format when converted to a string, so there isn't much more you need to do.
I have strings like:
first = '2018-09-16 15:00:00'
second = '1900-01-01 09:45:55.500597'
I want to compare them.
All methods I found like Convert string date to timestamp in Python requires to know the format of the string.
I don't know the format of the strings (see differences between first and second) all I know is that they can be converted to timestamps.
How can I convert them in order to compare them?
Edit:
The "largest" string that I can get is:
1900-01-01 09:45:55.500597
but I can also get:
1900-01-01
1900-01-01 09:45
1900-01-01 09:45:55
etc..
It's always YYYY-MM-DD HH-MM....
You can use pandas.to_datetime. It offers a lot of flexibility in the string timestamp format, and you can use it on single strings or list/series/tuples of timestamps.
>>> import pandas as pd
>>> day = pd.to_datetime('1900-01-01')
>>> minute = pd.to_datetime('1900-01-01 09:45')
>>> second = pd.to_datetime('1900-01-01 09:45:55')
>>> subsecond = pd.to_datetime('1900-01-01 09:45:55.500597')
>>> assert subsecond > second
>>> assert minute < second
>>> assert day < minute
You can use the dateutil module (pip install python-dateutil):
>>> from dateutil.parser import parse
>>> parse('2018-09-16 15:00:00')
datetime.datetime(2018, 9, 16, 15, 0)
>>> parse('1900-01-01 09:45:55.500597')
datetime.datetime(1900, 1, 1, 9, 45, 55, 500597)
From the list of its features:
Generic parsing of dates in almost any string format;
Once you have the datetime objects, you can compare them directly, there's no need to calculate the timestamps.
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' .
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"}}