Suppose that you have a variable that stores the following time zone format as string type:
timezone = '(GMT -5:00)'
Now you have the following times, which were set in GMT -4:00 time and as string types:
time1 = '4:00' #am (GMT -4:00)
time2 = '9:00' #am (GMT -4:00)
How can be used the variable timezone to change the time1 and time2 values to its corresponding local times? that is:
time1 = '3:00' #am (GMT -5:00)
time2 = '8:00' #am (GMT -5:00)
Figured it out, it ain't that great but it's honest work:
import datetime
timezone = '(GMT -5:00)'
timezone = timezone.replace("(", "").replace("GMT ", "").replace(":","").replace(")", "")
gmt_hours = int(timezone[:2])
gmt_less_4_hours = -4
time_difference = abs(gmt_hours - gmt_less_4_hours)
time1 = "04:00" #am (GMT -4:00)
time1 = datetime.datetime.strptime(time1, "%H:%M")
time1 -= datetime.timedelta(hours=time_difference)
time1 = time1.strftime('%H:%M')
print(time1)
time2 = '9:00' #am (GMT -4:00)
time2 = datetime.datetime.strptime(time2, "%H:%M")
time2 -= datetime.timedelta(hours=time_difference)
time2 = time2.strftime('%H:%M')
print(time2)
Output:
03:00
08:00
Related
Time should be sent in this format
"2023-01-09T10:45:00.000+05:30"
and the String which i have to parse into datetime is only "10:00 AM"
i tried doing this
var GMTdateFormat = DateFormat('yyyy-MM-ddHH:mm:ss.000+05:30').format(
DateTime.parse(
(state as SlotRequestPopUpDataLoadedState)
.slotStartTimingList
.where((element) => element.isSelected == true)
.map((e) => e.name)
.toString(),
).toUtc(),
);
But it is not working
try this:
//input: 10:00 AM
final time = DateFormat('hh:mm a').parse("10:00 AM");
final year = DateTime.now().year;
final month = DateTime.now().month;
final day = DateTime.now().day;
final dateString = DateFormat('$year-$month-${day}THH:mm:ss.SSS+05:30').format(time);
print(dateString); //2023-1-9T10:00:00.000+05:30
Hopefully just a simple question. I want to convert a datetime object to seconds and include the days. I've just noticed that my code skipped the day. Please note times are just an example and not 100% accurate.
Content of oldtime.txt (2 days ago):
2021-09-16 19:34:33.569827
Code:
oldtimefile = open('oldtime.txt', 'r+')
oldtme = oldtimefile.read()
datetimeobj = datetime.strptime(oldtme, "%Y-%m-%d %H:%M:%S.%f")
finaltime = datetime.now() - datetimeobj
print(finaltime.seconds)
If I just print finaltime then I get 1 day, 22:13:30.231916.
Now if we take today's date and time - just for argument sake - (2021-09-18 17:34:33.569827) as now then I actually get 80010 seconds instead of roughly 172800 seconds. It's ignoring the day part.
How can I include the day and convert the entire object to seconds?
Thanks.
Instead of .seconds you can use .total_seconds():
from datetime import datetime
oldtme = "2021-09-16 19:34:33.569827"
datetimeobj = datetime.strptime(oldtme, "%Y-%m-%d %H:%M:%S.%f")
finaltime = datetime.now() - datetimeobj
print(finaltime.total_seconds())
Prints:
164254.768354
I need to check if the string of timestamp belongs to 'UTC' timestamp
i have below code
def time_stamp():
utc = timezone('UTC')
time_stamp = datetime.now(utc)
utc_time_stmap = time_stamp.strftime("%Y-%m-%dT%H:%M:%S.%f")
return utc_time_stmap
the above function return the utc time in a string format
print(type(time_stamp()))
<class 'str'>
print(time_stamp())
'2021-02-10 15:49:57.906168'
The 'time_stamp()' return the timestamp in 'string type'.
#Expected:
i need to check the return value falls within a tight date UTC date range?
Appreciated for the the help?
Thanks
Here you get some code where you may find your answer.
import re
from datetime import datetime
DATETIME_ISO8601 = re.compile(
r'^([0-9]{4})' r'-' r'([0-9]{1,2})' r'-' r'([0-9]{1,2})' # date
r'([T\s][0-9]{1,2}:[0-9]{1,2}:?[0-9]{1,2}(\.[0-9]{1,6})?)?' # time
r'((\+[0-9]{2}:[0-9]{2})| UTC| utc)?' # zone
)
def datetime_iso(string):
""" verify rule
Mandatory is: 'yyyy-(m)m-(d)dT(h)h:(m)m'
"""
string = string.strip()
return bool(re.fullmatch(DATETIME_ISO8601, string))
def utc_timezone(datetime_string):
datetime_string = datetime_string.strip()
return datetime_string.endswith("00:00") or datetime_string.upper().endswith("UTC")
check_this = ["2020-1-1 22:11", "2020-1-1 22:11:34 00:00", "2020-1-1 22:11:34+00:00", "2020-1-1 22:11+01:00", "2020-1-1 22:11 UTC", "does this help?"]
for datetime_string in check_this:
print(".........................")
print(f"This date time string '{datetime_string}' is in datetime iso format: {datetime_iso(datetime_string)}")
if datetime_iso(datetime_string):
print(f"Is it the UTC time zone? {utc_timezone(datetime_string)}")
I want to print the amount of days, hours, minutes and seconds until christmas day but when it prints, it also gives me the millisecond. I tried doing print(remain_until_xmas.strip(.) but that didn't work. Here is the code
import datetime as dt
xmas = dt.datetime(2020, 12, 25)
now = dt.datetime.now()
until_xmas = xmas - now
print(until_xmas)
To get the time live, you can use this code:
import time
time = str(time.strftime("%M")) + ":" + str(time.strftime("%S"))
print(time)
This will give you the current time in Minutes and Seconds, and if you put it in a loop, it will keep updating itself.
If you want the day and month, you can use
print(time.strftime("%A, %B %e")) -
With this code, you can then subtract the Xmas date from the current date, and retrieve what you want.
This would be your final code:
import time
month = time.strftime("%m")
day = time.strftime("%d")
hour = time.strftime("%H")
minute = time.strftime("%M")
second = time.strftime("%S")
chrmonth = 12
chrday = 23
chrhour = 12
chrminute = 60
chrsecond = 60
print("The time until christmas is, ", int(chrmonth) - int(month), "months", int(chrday) - int(day), "days", int(chrhour) - int(hour), "hours", int(chrminute) - int(minute), "minutes", int(chrsecond) - int(second), "seconds")
Hopefully this helps!
you can use .strftime()
print(until_xmas.strftime("%m/%d/%Y, %H:%M:%S"))
see more here about strftime.
Time = datetime.datetime.now().time()
I wanted to find the difference in seconds between the Time above^ and the hour of the day:
for example if the Time = 15:07:25.097519, so the hour of the day is 15:00:00, i want to store 445.097519 seconds to a variable.
How can I do that?
I am an amateur at this please help!!
import datetime
now = datetime.datetime.now()
hour = now.replace(minute=0, second=0, microsecond=0)
seconds = (now - hour).seconds + (now - hour).microseconds / 1000000
Here is one way to do it. Extract the hour from current time, and initialize a new datetime.time object with hour as input. Then you convert both of the timestamps to datetime and then do the subtraction. Code below does that
Time = datetime.datetime.now().time()
hour = str(Time).split(":")[0]
currentHourTime = datetime.datetime(2019,10,31,int(hour),0,0,0).time()
dateTimeCurr = datetime.datetime.combine(datetime.date.today(), Time)
dateTimeCurrHour = datetime.datetime.combine(datetime.date.today(), currentHourTime)
dateTimeDifference = dateTimeCurr - dateTimeCurrHour
dateTimeDifferenceInSeconds = dateTimeDifference.total_seconds()
print(dateTimeDifferenceInSeconds)