How to change the date of time instance using python? - python

I have start_time variable that stores a time string.
start_time = '2022-12-21 22:00:00'
Now Using python i want to change the date of start time to
start_time = '2022-12-28 22:00:00'
I have done this with very ugly approach. Please tell me easy and best way to do that.
I tried with following code.
#its not string its time instance
replacing_date = 2022-12-28 00:00:00
#converting time into string
replacing_date = datetime.strptime(replacing_date,'%Y-%m-%d %H:%M:%S')
replacing_date =replacing_date.split(" ")
start_time = start_time.split(" ")
start_time = datetime.strptime(replacing_date[0]+start_time[1],'%Y-%m-%d %H:%M:%S')
Basically i have to change date on many places. It doesn't seems to be good thing in that case. and it can break if time string format changes.
it can also break if the years or month changes. for example date change to.
start_time = '2023-01-01 22:00:00'

You can use datetime.replace(..):
from datetime import datetime
start_time = "2022-12-21 22:00:00"
new_time = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S").replace(day=28)
print(new_time)
Output:
2022-12-28 22:00:00
Or regexp:
import re
new_time = re.sub(r"\d{4}-\d{2}-\d{2}", "2022-12-28", "2022-12-21 22:00:00", 0)
print(new_time)
Output:
2022-12-28 22:00:00

from datetime import datetime, timedelta
start_time = '2022-12-21 22:00:00'
replacing_date = datetime.strptime(start_time,'%Y-%m-%d %H:%M:%S')
new_time = replacing_date+timedelta(days=7)
print(new_time)
Output:
2022-12-28 22:00:00
use timedelta to change time.

Related

How to subtract minutes from a python time object

If I have a python time object
import datetime
my_time = datetime.time(2,30,00)
What is the best way of subtracting ten minutes from "my_time"? Please note if time is 00:05:00 for example, expected result of this subtraction is 23:55:00.
I found a way to do it, but it feels like there's probably a better way. Also, I will prob have issues with timezone, using this way. Here it is:
import datetime
my_time = datetime.time(2,30,00)
temp_date = datetime.datetime.combine(datetime.datetime.today(), my_time)
temp_date = temp_date - datetime.timedelta(minutes=10)
my_time = temp_date.time()
So essentially I first convert time back to datetime, do the operation I want, and then convert it back to time.
One way is to make a timedelta object, which supports subtraction.
from datetime import timedelta
time_1 = timedelta(hours=2, minutes=30, seconds=00)
time_2 = timedelta(hours=00, minutes=5, seconds=00)
delta = timedelta(minutes=10)
print(time_1 - delta)
print(time_2 - delta)
# Out
# 2:20:00
# -1 day, 23:55:00

Get GMT timestamp in python

I need to get GMT timestamps, a timestamp when start a day, and another when end a day, the following example is for today (2022-03-29):
Start of Day (Unix Timestamp): 1648512000
End of Day (Unix Timestamp): 1648598399
you can check this in https://www.epochconvert.com/
and my code only for the case of start of day is the next one :
from datetime import datetime
start_date = datetime.today().strftime('%Y-%m-%d')
start_date += ' 00:00:00'
print(start_date)
timestamp = time.mktime(datetime.strptime(start_date, "%Y-%m-%d %H:%M:%S").timetuple())
print(timestamp)
and my output:
2022-03-29 00:00:00
1648533600.0
as you can see it's not the answer I'm waiting for, that timestamp is for my Local Time but i need a GMT timestamp as answer (1648512000 in this case)
How could i do it ?
Thanks in Advance!!
if you want to derive Unix time from datetime objects, make sure to set time zone / have aware datetime:
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
print(now)
# 2022-03-29 23:34:51.701712+00:00
now_floored = datetime.combine(now.date(), now.time().min).replace(tzinfo=timezone.utc)
print(now_floored)
# 2022-03-29 00:00:00+00:00
now_floored_unix = now_floored.timestamp()
print(now_floored_unix)
# 1648512000.0
If you do not do that (have naive datetime), Python will use local time:
now = datetime.now()
now_floored = datetime.combine(now.date(), now.time().min)
print(now_floored.astimezone())
# 2022-03-29 00:00:00-06:00 # <- my current UTC offset is -6 hours
print(now_floored.timestamp(), (now_floored_unix-now_floored.timestamp())//3600)
# 1648533600.0 -6.0

python strftime apply timezone or add 3 hours

I want to apply timezone for meeting_time.strftime
def format_filename(recording, file_type, recording_type):
uuid = recording['uuid']
topic = recording['topic'].replace('/', ' ').replace(':', '').replace('?', '')
rec_type = recording_type.replace("_", " ").title()
meeting_time = parse(recording['start_time'])
return '{} - {} UTC - {}.{}'.format(
meeting_time.strftime('%Y.%m.%d'), meeting_time.strftime('%H.%M %p'), topic+" - "+rec_type, file_type.lower())
Example of filename I got with code above- 2020.12.02 - 10.00
Filename I want - 2020.12.02 - 13.00
Original code - https://github.com/ricardorodrigues-ca/zoom-recording-downloader
You can use datetime and timedelta.
from datetime import datetime, timedelta
print((datetime.now() + timedelta(hours=3)).strftime('%Y.%m.%d - %H.%M'))
Output
2020.12.02 - 14.39
This will print the time after 3 hours from now.
Take a look at this code:
from datetime import datetime, timedelta
d = '2020.12.02 - 10.00'
result = datetime.strftime(datetime.strptime(d, '%Y.%m.%d - %H.%M') + timedelta(hours=3), '%Y.%m.%d - %H.%M')
The result will be:
'2020.12.02 - 13.00'
If all you want to do is add 3 hours, you can do it as:
new_datetime = datetime.datetime.today() + datetime.timedelta(hours=3)
This adds 3 hours to your previous datetime.
If you want to make use of timezone's, you can find about it in Python's official documentation: https://docs.python.org/3.7/library/datetime.html#datetime.tzinfo
Let us make time conversion in a standard and robust way:
In order to covert time between zones:
1- Spcify the zone in which DateTime was recorded.
2- Convert the scpecified DateTime to the required time zone.
The mentioned steps are explained in the followin example:
from datetime import datetime
from pytz import timezone
# Choose any datetime
datetime_local=datetime(2020,12,2,10,00)
print(datetime_local)
# specifiy/include the time zone in the datetime for example ('Brazil/East') (-3.00)
datetime_brazil = timezone('Brazil/East').localize(datetime_local)
print('Brazil')
print(datetime_brazil)
# Convert it to UTC time zone
datetime_utc = datetime_brazil.astimezone(timezone('Etc/Universal'))
print('UTC')
print(datetime_utc)
# Convert the time to Cairo time zone
datetime_cairo = datetime_brazil.astimezone(timezone('Africa/Cairo'))
print('Cairo')
print(datetime_cairo)
The output
2020-12-02 10:00:00
Brazil
2020-12-02 10:00:00-03:00
UTC
2020-12-02 13:00:00+00:00
Cairo
2020-12-02 15:00:00+02:00
We Can get the list of time zone by the followin code:
import pytz
for tz in pytz.all_timezones:
print(tz)
the output list:
Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
...
...
Applying the steps mentioned above to the code in the question,
if the recorded DateTime was in Brazil and we want to convert it to UTC so we modify the code as follows:
def format_filename(recording, file_type, recording_type):
uuid = recording['uuid']
topic = recording['topic'].replace('/', ' ').replace(':', '').replace('?', '')
rec_type = recording_type.replace("_", " ").title()
meeting_time = parse(recording['start_time'])
# Start of modification
# Sepcify the local time zone, (localize it)
meeting_timt_local = timezone('Brazil/East').localize(meeting_time)
# Convert specified/localized DateTime to utc
meeting_time_utc = meeting_timt_local.astimezone(timezone('Etc/Universal'))
# return the formated meeting_time in utc
return '{} - {} UTC - {}.{}'.format(
meeting_time_utc.strftime('%Y.%m.%d'), meeting_time_utc.strftime('%H.%M %p'), topic+" - "+rec_type, file_type.lower())
Goog Luck

How to read a text as today's time in python? [duplicate]

This question already has answers here:
Parse only time, and set date to today?
(3 answers)
Closed 2 years ago.
When I try to convert a string that contains some time in the format of 13:00, it is keeping the date field as 1900-01-01 13:00:00.
But I want to keep today's' date there.
import datetime as dt
sTime = "13:00"
sTime = dt.datetime.strptime(sTime, '%H:%M')
Any suggestions?
Use combine:
import datetime as dt
sTime = "13:00"
sTime = dt.datetime.strptime(sTime, '%H:%M')
print(dt.datetime.combine(dt.datetime.today(), sTime.time()))
outputs
2020-08-28 13:00:00
Or directly but with a bit more work:
import datetime as dt
sTime = "13:00"
sTime = dt.datetime.strptime(sTime, '%H:%M')
today = dt.datetime.today()
print(dt.datetime(today.year, today.month, today.day, sTime.hour, sTime.minute, sTime.second))
import datetime as dt
sTime = "13:00"
# PARSE string to datetime object
objDateTime = dt.datetime.strptime(sTime, "%H:%M")
# combine PARSED time from sTime with today's date
objDateTime = dt.datetime.combine(dt.datetime.today(), objDateTime.time())
# FORMAT objDateTime to Hr:Min string output
print(objDateTime.strftime("%H:%M"))
# FORMAT objDateTime to DD-MMM-YYYY Hr:Min string output
print(objDateTime.strftime("%d-%b-%Y %H:%M"))
Output (when run on 28-Aug-2020)
13:00
28-Aug-2020 13:00

Add duration to time in python

I have two strings:
current_time : 4:46:00 PM
duration : 03:20:00
current_time is : %I:%M:%S %p
duration is hour:minute:seconds format.
I have to add the duration in the time .
In the above case : I need to get the output as : 08:06:00 PM
The code that I have tried is :
parsedtime = time.strptime(current_time,"%I:%M:%S %p")
parsedduration = time.strptime(duration,"%I:%M:%S")
parsedtime + datetime.timedelta(parsedduration.tm_hour,parsedduration.tm_min,parsedduration.tm_sec)
print parsedtime
The above is obviously incorrect and not working , please suggest the optimal way.
Your problem is mixing time and datetime objects and not naming your keyword arguments in timedelta.
from datetime import datetime, timedelta
current_time = "4:46:00 PM"
duration = "3:20:00"
parsed_time = datetime.strptime(current_time, "%I:%M:%S %p")
parsed_duration = datetime.strptime(duration, "%I:%M:%S")
then = parsed_time + timedelta(hours=parsed_duration.hour,
minutes=parsed_duration.minute,
seconds=parsed_duration.second)
result = then.strftime("%I:%M:%S %p")
# 08:06:00 PM
import datetime
today1= datetime.date.today()
difference= datetime.timedelta(1)
yesterday= today1 - difference
print (yesterday)
It will give you a point, for example this one finds today-1day. It means yesterday.
time1= time.localtime()
hour1=time1.tm_hour
min1=tim1.tm_min
#do your codes#
So you can define hour and min as a variable and do math.

Categories