How to change the secs to the ISO time format:
for example:
28800 sec is the offset from the midnight? if successfully converted, the output should be 08:00:00 not 8:00:00.
How could I do it in python? Thank you.
Solution using timedelta to 'do the math'
from datetime import datetime, timedelta
# Can easily get the values for today programmatically
# but ommitted here for brevity
midnight = datetime(2013, 10, 18)
delta = timedelta(seconds=28800)
offset_time = midnight + delta
print offset_time.strftime('%H:%M:%S')
>>> 08:00:00
Related
I want to format timestamp to day -1 but require a format
I am getting day-1 exactly minus 24 hrs but I need from midnight onwards
from datetime import datetime,timedelta
import pytz
partdate=datetime.today().strftime('%Y-%m-%d %H:%M:%S')
# print(partdate)
# import pytz
tzinfo=pytz.timezone('US/Eastern')
# print(tzinfo)
x=(datetime.now() + timedelta(days=-1)) # Here
tzinfo=pytz.timezone('US/Eastern')
pardate1=tzinfo.localize(datetime.now()+timedelta(days=-1),is_dst=None)
print(pardate1)
#print('x----->',x)
#print('timevalue',tzinfo)
# yesterday = datetime.today() - timedelta(days = 1 )
# print(yesterday)
output is 2022-08-13 20:39:26.232974-04:00
But required output is 2022-08-13T00:00:000Z
IIUC, you want date/time now in a certain time zone, subtract one day, then convert to UTC, then 'floor' that date/time to midnight.
Here's a step-by-step example how you can do that. Note that I use zoneinfo since pytz is deprecated and time zone name "America/New_York" as "US/Eastern" is obsolte as well.
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
now = datetime.now(ZoneInfo("America/New_York"))
daybefore = now - timedelta(days=1)
daybefore_UTC = daybefore.astimezone(ZoneInfo("UTC"))
daybefore_UTC_midnight = daybefore_UTC.replace(hour=0, minute=0, second=0, microsecond=0)
print(now)
print(daybefore_UTC_midnight)
# 2022-08-15 03:38:42.006215-04:00
# 2022-08-14 00:00:00+00:00
Say I have the datetime now:
import datetime
now = datetime.datetime(2019, 10, 3, 1, 57, 3, 939862)
print(now)
2019-10-03 01:57:03.939862
and I have a timedelta for the start of business day (07:00:00).
start_biz_dt = datetime.timedelta(hours = 7)
I want to do a calculation that gives me the time from now to start of business day.
ie, I want:
6:03:56.060138
But I obviously cannot do:
start_biz_dt - now
I could give start_biz_dt the same date as now, but I have many datetimes in a column of various dates, so this might not be the best way. Any help is appreciated.
To find closest 07:00:00, so you can use next code:
from datetime import datetime, timedelta
start_of_business_day = datetime.now().replace(hour=7, minute=0, second=0)
if start_of_business_day < datetime.now():
start_of_business_day += timedelta(days=1)
To calculate how much left just substitute current datetime from start_of_business_day:
sleep_time = start_of_business_day - datetime.now()
I am trying to convert unix time on my local system to UTC time in unix format, but after converting it the final time is going off by +1 hour.
To do so, I wrote the following code.
from dateutil import tz
import time
from time
import mktime
now_time = time.time()
print('current local unix time', now_time)
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now_time)))
to_zone = tz.tzutc()
from_zone = tz.tzlocal()
t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now_time))
utc = datetime.strptime(str(t), '%Y-%m-%d %H:%M:%S')
utc = utc.replace(tzinfo=from_zone)
central = utc.astimezone(to_zone)
print('Converted to UTC ',central)
unix_secs = mktime(central.timetuple())
print('Central unix time ',unix_secs)
print('central unix time to dattime ', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(unix_secs)))
The output is as follows
current local unix time 1563985835.3707478
2019-07-24 12:30:35
Converted to UTC 2019-07-24 16:30:35+00:00
Central unix time 1564003835.0
central unix time to dattime 2019-07-24 17:30:35
can someone please tell me what am I doing wrong here and how can I fix this?
I guess you're incorrectly transform datetimes with TZ information when converting the timestamp to datetime instance using time.strftime and after that datetime.strptime or when using mktime.
Anyway, there is much easier way to achieve what you want:
from datetime import datetime, timezone
# Get current timestamp
now_timestamp = time.time()
>> 1563987839.054703
# Get datetime of that timestamp but already in UTC.
# This preserves TZ information and allows
# to correctly do transition to the timestamp again.
utc_time = datetime.utcfromtimestamp(now_timestamp)
>> datetime.datetime(2019, 7, 24, 17, 3, 59, 54703)
# Convert UTC datetime back to timestamp
utc_timestamp = utc_time.timestamp()
>> 1563977039.054703
# Verify that this timestamp is indeed UTC
# I am in UTC+3 timezone now
datetime.now()
>> datetime.datetime(2019, 7, 24, 20, 4, 10, 500229)
datetime.fromtimestamp(utc_timestamp)
>> datetime.datetime(2019, 7, 24, 17, 3, 59, 54703)
A Unix timestamp is always in UTC.
It is "the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, UTC".
In other words, it's the duration. It doesn't matter in the slightest where you do this calculation. Subtraction works the same everywhere in the universe. Durations have absolutely nothing to do with timezones.
Reference - https://en.wikipedia.org/wiki/Unix_time
I am using Python to access the mobile API of some web service and the response contains the following weird Date notation: u'/Date(1409522400000+0200)/' This should be the 1st of September, 2014.
I am not sure which format this is, but I would like to convert this to something readable, i.e. a date or a datetime or Unix time.
Can anybody help me with this?
The time string looks like OData version 2 JSON verbose format for Datetime that may be seen in old ASP.NET or WCF applications:
“/Date(<ticks>[“+” | “-” <offset>])/”
<ticks> = number of milliseconds
since midnight Jan 1, 1970
<offset> = utc offset
#!/usr/bin/env python3
import re
from datetime import datetime, timedelta, timezone
time_string = u"/Date(1409522400000+0200)/"
epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
ticks, offset = re.match(r'/Date\((\d+)([+-]\d{4})?\)/$', time_string).groups()
utc_dt = epoch + timedelta(milliseconds=int(ticks))
print(utc_dt)
if offset:
offset = int(offset)
hours, minutes = divmod(abs(offset), 100)
if offset < 0:
hours, minutes = -hours, -minutes
dt = utc_dt.astimezone(timezone(timedelta(hours=hours, minutes=minutes)))
print(dt)
Output
2014-08-31 22:00:00+00:00
2014-09-01 00:00:00+02:00
where timezone is defined here.
you received a (java?) timestamp in milliseconds. you can convert it to something more readable like so:
from datetime import date
d=1409522400000/1000.0 # divide by 1000 to get seconds
print date.fromtimestamp(d) # -> 2014-09-01
I am trying to get the date to be yesterday at 11.30 PM.
Here is my code:
import datetime
yesterday = datetime.date.today () - datetime.timedelta (days=1)
PERIOD=yesterday.strftime ('%Y-%m-%d')
new_period=PERIOD.replace(hour=23, minute=30)
print new_period
however i am getting this error:
TypeError: replace() takes no keyword arguments
any help would be appreciated.
First, change datetime.date.today() to datetime.datetime.today() so that you can manipulate the time of the day.
Then call replace before turning the time into a string.
So instead of:
PERIOD=yesterday.strftime ('%Y-%m-%d')
new_period=PERIOD.replace(hour=23, minute=30)
Do this:
new_period=yesterday.replace(hour=23, minute=30).strftime('%Y-%m-%d')
print new_period
Also keep in mind that the string you're converting it to displays no information about the hour or minute. If you're interested in that, add %H for hour and %M for the minute information to your format string.
You can use datetime.combine(date, time, tzinfo=self.tzinfo)
import datetime
yesterday = datetime.date.today () - datetime.timedelta (days=1)
t = datetime.time(hour=23, minute=30)
print(datetime.datetime.combine(yesterday, t))
Is this what you want?
from datetime import datetime
yesterday = datetime(2014, 5, 12, 23, 30)
print yesterday
Edited
from datetime import datetime
import calendar
diff = 60 * 60 * 24
yesterday = datetime(*datetime.fromtimestamp(calendar.timegm(datetime.today().utctimetuple()) - diff).utctimetuple()[:3], hour=23, minute=30)
print yesterday