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
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
I am trying to set startdate and enddate in python but ran across some problem. What i want is start date set to beginning of the year and enddate set to one day prior to current date.
from datetime import datetime, timedelta, time,date
my_str= '2020-01-01'
stdate= datetime.strptime(my_str,'%Y-%m-%d')
print(stdate)
edate = datetime.now() - timedelta(days = 1)
print(edate)
Right now the output is date with time.But i only want to output date not time
2020-01-01 00:00:00
2020-03-01 12:25:50.542813
from datetime import date, timedelta
start_of_current_year = date(date.today().year, 1, 1)
end_of_previous_year = start_of_current_year - timedelta(days=1)
# Check values
print(start_of_current_year)
print(end_of_previous_year)
I wanted to add a minute to the date which is in the Hive timestamp format of 'YYYY-MM-DD HH24:MI:SS.FF6' using Python
Example:1) 2015-01-15 08:59:16 date after adding a minute should become 2015-01-15 09:00:16
2)
For this, I got the minute part from the date and added 1 to it with a modulo 60:
str((int(csvRowArray[1][10:12])+ 1)%60)
Here csvRowArray[1] is the date in string format.
The problem comes when the minute is 59, although it resets the minute part to 0, the hour part doesn't increase. This should also work when the hour is 23:59 and we add a minute, the date should change.Or if the date is at the end of the month and the hour is 23:59 then even the month should change!
Is there a function in Python to read the date in Hive timestamp format and add a minute to it?
It will help if you can convert the object into DateTime instances as that will allow you to manipulate the time directly using timedelta. Taking your example of '2015-01-15 08:59:16'
from datetime import datetime as dt
from datetime import timedelta
a='2015-01-15 08:59:16'
dt_obj = dt.strptime(a, '%Y-%m-%d %H:%M:%S')
dt_with_one_more_min = dt_obj + timedelta(minutes=1)
print('original time = {}'.format(dt_obj))
print('new time = {}'.format(dt_with_one_more_min))
This will give the following result:
original time = 2015-01-15 08:59:16
new time = 2015-01-15 09:00:16
My example is with minutes, but you can try other modifications too with timedelta and it will work.
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 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.