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

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

Related

Convert YYYY-MM-DD to DD-MMM-YYYY in Python [duplicate]

This question already has answers here:
Parse date string and change format
(10 answers)
Closed 24 days ago.
I'm trying to convert a list of dates (strings) in the format 2023-01-19 into the format 19-Jan-2023. The code I currently have does not work:
date_list = ['2023-01-19', '2023-01-07', '2022-11-29']
new_date_list = []
for date in date_list:
date_new_format = datetime.datetime(date, '%dd-%mmm-%yyyy')
new_date_list.append(date_new_format)
You have to first create a datetime object with strptime, then you can use strftime to reformat it:
from datetime import datetime
date_list = ['2023-01-19', '2023-01-07', '2022-11-29']
for date in date_list:
d = datetime.strptime(date, "%Y-%m-%d")
date_new_format = datetime.strftime(d, '%d-%b-%Y')
print(date_new_format)

How to change the date of time instance using 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.

subtract one day from timestamp - python

'I'm trying to subtract a day from this date 1590074712 in order to make 1590008151 but can't figure out any way to achieve that.
I've tried with:
from datetime import datetime
ts= 1590074712
date = datetime.timestamp(ts) - timedelta(days = 1)
print(date)
How can I subtract a day from a date in the above format?
I want the output in timestamp
Use datetime.fromtimestamp():
from datetime import datetime, timedelta
ts= 1590074712
date = datetime.fromtimestamp(ts) - timedelta(days = 1)
print(date)
Prints:
2020-05-20 15:25:12

Python parse string date [duplicate]

This question already has answers here:
Convert timestamps with offset to datetime obj using strptime
(4 answers)
Closed 3 years ago.
I have string like this:
2019-04-03 05:10:35+03:00
I need to output date like this:
2019-04-03 08:10:35
My code:
print(datetime.strptime(str("2019-04-03 05:10:35+03:00"), "%Y-%m-%d %H:%M:%S%z"))
but I have error:
ValueError: time data '2019-04-03 05:10:35+03:00' does not match
format '%Y-%m-%d %H:%M:%S%z'
This will work
from datetime import datetime
your_date = datetime.strptime("2019-04-03 05:10:35+03:00", "%Y-%m-%d %H:%M:%S%z")
print(your_date.strftime("%Y-%m-%d %H:%M:%S"))
EDIT:
You have "+03:00" if you count timezone, if you want to add that to your result, do it like this:
from datetime import datetime
your_date = datetime.strptime("2019-04-03 05:10:35+03:00", "%Y-%m-%d%H:%M:%S%z")
print((your_date + timedelta(0, your_date.tzinfo.utcoffset(your_date).seconds)).strftime("%Y-%m-%d %H:%M:%S"))
The problem is that your input string is improperly formatted. %z expects a string of format +HHMM or -HHMM; you have an extra :.
Accordingly, you could use a regex to format it:
import re
source = '2019-04-03 05:10:35+03:00'
formatted = re.sub(r'([+-])(\d\d):(\d\d)', r'\1\2\3', source)
print(datetime.strptime(formatted, "%Y-%m-%d %H:%M:%S%z").astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S"))
Output:
2019-04-03 02:10:35
Using datetime and split() for str manipulation:
Assuming it to be + hours:
from datetime import datetime, timedelta
dt_1 = "2019-04-03 05:10:35+03:00"
date_ = dt_1.split("+")[0]
time_ = date_.split(" ")[1]
to_add = dt_1.split("+")[1]
d = datetime.strptime(date_, "%Y-%m-%d %H:%M:%S")
t = datetime.strptime(time_, "%H:%M:%S")
d += timedelta(hours=int(to_add.split(":")[0]), minutes=int(to_add.split(":")[1]))
print(d)
OUTPUT:
2019-04-03 08:10:35

How to convert GMT time to EPOCH Timestamp in milliseconds in python? [duplicate]

This question already has answers here:
How can I convert a datetime object to milliseconds since epoch (unix time) in Python?
(14 answers)
Closed 7 years ago.
I want to change GMT Zone(date and time) to EPOCH Time stamp in milliseconds.
For example:
I want to take current system date and by default the time will be "16:00:00" and convert this date & time like below:
If Date & Time is "12/15/2015 16:00:00" GMT to be converted to "1450195200000"
Here the code i used to achieve but no solution:
import datetime
dt = time.strftime("%d/%m/%Y ")
ti = "16:00:00"
dt_ti = dt + ti
pattern = '%d/%m/%Y %H:%M:%S'
epoch = int(time.mktime(time.strptime(dt_ti, pattern)))
print (epoch)
output is 1450175400
But i want to achieve is this 1450195200000
Please help me on this.
time.mktime assumes the time_struct you feed it is local time. calendar.timegm() does something similar but assumes you give it a UTC time_struct.
import datetime
import calendar
dt = time.strftime("15/12/2015 ")
ti = "16:00:00"
dt_ti = dt + ti
pattern = '%d/%m/%Y %H:%M:%S'
epoch = int(time.mktime(time.strptime(dt_ti, pattern)))
print (epoch)
# 1450224000
utc_epoch = int(calendar.timegm(time.strptime(dt_ti, pattern)))
print (utc_epoch)
# 1450195200

Categories