python convert 10 digits datetimestamp to 13 digit GMT timestamp [duplicate] - python

This question already has answers here:
How do I get the current time in milliseconds in Python?
(16 answers)
Closed 3 years ago.
I receive a timestamp from a server like this 1512543958 & when i send back requests in headers i see a 13 digit GMT time stamp like this 1512544485819
By changing the time to local using the code below i get 2017-12-06 12:35:58
print(datetime.datetime.fromtimestamp(int("1512544474")).strftime('%Y-%m-%d %H:%M:%S')
& when i apply the code below i get 'Wed 06 Dec 2017 07:14:45 GMT'
time.strftime("%a %d %b %Y %H:%M:%S GMT", time.gmtime(1512544485819 / 1000.0))
So basically i need a python function that takes the 10 digit date timestamp as argument & returns 13 digit GMT date timestamp
example input 1512544474
expected output 1512544485819

I am using python 2.7
import time
import datetime
import time as mod_time
from datetime import datetime
from datetime import datetime, timedelta
from datetime import date, timedelta
today = datetime.now()
yesterday = datetime.now() - timedelta(days=1)
today_time = int((mod_time.mktime(today.timetuple())))
yesterday_time = int((mod_time.mktime(yesterday.timetuple())))
today_unixtime = (today_time*1000)
yesterday_unixtime = (yesterday_time*1000)
print("today timestamp =", today_unixtime)
print("yesterday timestamp =", yesterday_unixtime)
Output
('today timestamp =', 1579243097000)
('yesterday timestamp =', 1579156697000)
You can check the current time stamp from crome browser console.
new Date(1579243097000)
it will gives you a current date and time.

Related

Extract each year, month, day, year from getctime , getmtime in Python

I want to extract the year month day hours min eachly from below value.
import os, time, os.path, datetime
date_of_created = time.ctime(os.path.getctime(folderName))
date_of_modi = time.ctime(os.path.getmtime(folderName))
Now I only can get like below
'Thu Dec 26 19:21:37 2019'
but I want to get the the value separtly
2019 // Dec(Could i get this as int??) // 26
each
I want to extract each year month day each time min value from date_of_created and date_of_modi
Could i get it? in python?
You can convert the string to a datetime object:
from datetime import datetime
date_of_created = datetime.strptime(time.ctime(os.path.getctime(folderName)), "%a %b %d %H:%M:%S %Y") # Convert string to date format
print("Date created year: {} , month: {} , day: {}".format(str(date_of_created.year),str(date_of_created.month),str(date_of_created.day)))
The time.ctime function returns the local time in string form. You might want to use the time.localtime function, which returns a struct_time object which contains the information you are looking for. As example,
import os, time
date_created_string = time.ctime(os.path.getctime('/home/b-fg/Downloads'))
date_created_obj = time.localtime(os.path.getctime('/home/b-fg/Downloads'))
print(date_created_string) # Mon Feb 10 09:41:03 2020
print('Year: {:4d}'.format(date_created_obj.tm_year)) # Year: 2020
print('Month: {:2d}'.format(date_created_obj.tm_mon)) # Month: 2
print('Day: {:2d}'.format(date_created_obj.tm_mday)) # Day: 10
Note that these are integer values, as requested.
time.ctime([secs])
Convert a time expressed in seconds since the epoch to a string of a form: 'Sun Jun 20 23:21:05 1993' representing local time.
If that's not what you want... use something else? time.getmtime will return a struct_time which should have the relevant fields, or for a more modern interface use datetime.datetime.fromtimestamp which... returns a datetime object from a UNIX timestamp.
Furthermore, using stat would probably more efficient as it ctime and mtime will probably perform a stat call each internally.
You can use the datetime module, more specifically the fromtimestamp() function from the datetime module to get what you expect.
import os, time, os.path, datetime
date_of_created = datetime.datetime.fromtimestamp(os.path.getctime(my_repo))
date_of_modi = datetime.datetime.fromtimestamp(os.path.getmtime(my_repo))
print(date_of_created.strftime("%Y"))
Output will be 2020 for a repo created in 2020.
All formats are available at this link

Calculate the time delay between send and received packets using iperf3 and tcpdump?

I have written a bash code to run iperf3 and capture packets. Then i have extracted frame time from the .pcap file using tshark. The time is in the following format Jan 27, 2020 13:22:12.683438000 CET.
Now i want to calculate the time difference between the sent and received packets, but I dont know how do i subtract time which is in this format.
Which variable type should i use so that I can perform the subtraction.
I have also used datetime library but did not get results.
check if below lines can help you
from datetime import datetime
from pytz import timezone
CET = timezone('CET')
send_time = datetime.strptime('11:18:57.925 Wed Jan 5 2019', '%H:%M:%S.%f %a %b %d %Y')
print(send_time.astimezone(CET))
difference_from_now = send_time.astimezone(CET) - datetime.now().astimezone(CET)
print(difference_from_now)
received_time = datetime.strptime('08:18:57.925 Mon Jan 20 2020', '%H:%M:%S.%f %a %b %d %Y')
print(received_time.astimezone(CET))
difference_send_received = send_time.astimezone(CET) - received_time.astimezone(CET)
print(difference_send_received)

Convert readable date to timestamp, timestamp to readable date before Epoch Time (1 January 1970)

I made a simple functions which converts date to timestamp and timestamp to date. However, the problem is that it's not working if the timestamp is negative and the date is before and even on 1 January 1970. Can you please help me? I can't find any sources related to this. I can solve this problem with raw MySQL but I am using now with pyDAL so I have no choice but to use Python in calculating these convertion.
import datetime
import time
def date(timestamp):
return datetime.datetime.utcfromtimestamp(int(timestamp)) \
.strftime('%d %B %Y')
def timestamp(date):
return int(time.mktime(
datetime.datetime.strptime(date, '%d %B %Y').timetuple()))
print(date('0'))
# 01 January 1970
print(date('-839939'))
# OSError: [Errno 22] Invalid argument
print(timestamp('31 December 1969'))
# OverflowError: mktime argument out of range
print(timestamp('1 January 1970'))
# OverflowError: mktime argument out of range
print(timestamp('2 January 1970'))
# 57600

Python get last month and year

I am trying to get last month and current year in the format: July 2016.
I have tried (but that didn't work) and it does not print July but the number:
import datetime
now = datetime.datetime.now()
print now.year, now.month(-1)
If you're manipulating dates then the dateutil library is always a great one to have handy for things the Python stdlib doesn't cover easily.
First, install the dateutil library if you haven't already:
pip install python-dateutil
Next:
from datetime import datetime
from dateutil.relativedelta import relativedelta
# Returns the same day of last month if possible otherwise end of month
# (eg: March 31st->29th Feb an July 31st->June 30th)
last_month = datetime.now() - relativedelta(months=1)
# Create string of month name and year...
text = format(last_month, '%B %Y')
Gives you:
'July 2016'
now = datetime.datetime.now()
last_month = now.month-1 if now.month > 1 else 12
last_year = now.year - 1
to get the month name you can use
"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()[last_month-1]
An alternative solution using Pandas which converts today to a monthly period and then subtracts one (month). Converted to desired format using strftime.
import datetime as dt
import pandas as pd
>>> (pd.Period(dt.datetime.now(), 'M') - 1).strftime('%B %Y')
u'July 2016'
You can use just the Python datetime library to achieve this.
Explanation:
Replace day in today's date with 1, so you get date of first day of this month.
Doing - timedelta(days=1) will give last day of previous month.
format and use '%B %Y' to convert to required format.
import datetime as dt
format(dt.date.today().replace(day=1) - dt.timedelta(days=1), '%B %Y')
>>>'June-2019'
from datetime import date, timedelta
last_month = date.today().replace(day=1) - timedelta(1)
last_month.strftime("%B %Y")
date.today().replace(day=1) gets the first day of current month, substracting 1 day will get last day of last month
def subOneMonth(dt):
day = dt.day
res = dt.replace(day=1) - datetime.timedelta(days =1)
try:
res.replace(day= day)
except ValueError:
pass
return res
print subOneMonth(datetime.datetime(2016,07,11)).strftime('%d, %b %Y')
11, Jun 2016
print subOneMonth(datetime.datetime(2016,01,11)).strftime('%d, %b %Y')
11, Dec 2015
print subOneMonth(datetime.datetime(2016,3,31)).strftime('%d, %b %Y')
29, Feb 2016
from datetime import datetime, timedelta, date, time
#Datetime: 1 month ago
datetime_to = datetime.now().replace(day=15) - timedelta(days=30 * 1)
#Date : 2 months ago
date_to = date.today().replace(day=15) - timedelta(days=30 * 2)
#Date : 12 months ago
date_to = date.today().replace(day=15) - timedelta(days=30 *12)
#Accounting standards: 13 months ago of pervious day
date_ma = (date.today()-timedelta(1)).replace(day=15)-timedelta(days=30*13)
yyyymm = date_ma.strftime('%Y%m') #201909
yyyy = date_ma.strftime('%Y') #2019
#Error Range Test
from datetime import datetime, timedelta, date, time
import pandas as pd
for i in range(1,120):
pdmon = (pd.Period(dt.datetime.now(), 'M')-i).strftime('%Y%m')
wamon = (date.today().replace(day=15)-timedelta(days=30*i)).strftime('%Y%m')
if pdmon != wamon:
print('Incorrect %s months ago:%s,%s' % (i,pdmon,wamon))
break
#Incorrect 37 months ago:201709,201710
import datetime as dt
.replace(day=1) replaces today's date with the first day of the month, simple
subtracting timedelta(1) subtracts 1 day, giving the last day of the previous month
last_month = dt.datetime.today().replace(day=1) - dt.timedelta(1)
user wanted the word July, not the 6th month so updating %m to %B
last_month.strftime("%Y, %B")

Handling of timezones in strptime in Python [duplicate]

This question already has answers here:
How to parse dates with -0400 timezone string in Python?
(6 answers)
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 6 years ago.
I have two string like these:
"Sun 10 May 2015 13:54:36 -0700"
"Sun 10 May 2015 13:54:36 +0000"
(The last part is time zone -0700 means 7 hours less than GMT)
My intention is turn it to a unix timestamp to find their absolute difference easily.
My Question is is there a built-in method for turning these formated texts to Unix timestamp? Or Is there a one that computes difference of two such strings directly??
Edit:
This Question differs from This one since that problem doesn't include time zones and not any of answers to that question mentioned anything about time zone.
This should work on Python 3 & above but not known to work on all platforms on Python 2.
date_str = "Sun 10 May 2015 13:54:36 -0700"
pattern = '%a %d %B %Y %H:%M:%S %z'
dt = int(time.mktime(time.strptime(date_str ,pattern )))
print(dt)
For, Python 2.7+, (without %z)
import datetime
date_str = "Sun 10 May 2015 13:54:36 -0700"
dt_str = date_str[:-5].strip()
dt_zone = int(date_str[-5:])/100
pattern = '%a %d %B %Y %H:%M:%S'
dtobj = datetime.datetime.strptime(dt_str ,pattern)
dt = dtobj + datetime.timedelta(hours=dt_zone)
print( dt.strftime('%s') )
This code answer to your question:
from datetime import timedelta, datetime, tzinfo
date1="Sun 10 May 2015 13:54:36 -0700"
date2=date1[4:-6]
zone = int(date1[-5:])/100
d=datetime.strptime(date2, "%d %B %Y %H:%M:%S")
class TZ(tzinfo):
def utcoffset(self, dt): return timedelta(hours=zone)
d=datetime(d.year, d.month, d.day,d.hour,d.minute,d.second, tzinfo=TZ()).isoformat(' ')
print d

Categories