This question already has answers here:
Checking date against date range in Python
(5 answers)
Closed 4 years ago.
new programmer just getting started with Python.
How would I be able to print out a list of timestamps, every second, given a date range, for example 4/12/17 through 4/21/17 in date -d format?
The output would be something along the lines of
Wed Apr 12 00:00:00 CST 2017
Wed Apr 12 00:00:01 CST 2017
.
.
.
Fri Apr 21 00:00:00 CST 2017
It would ideally be in a nice, vertical list for the output.
I am guessing the solution involves nested for loops, but I just can't wrap my head around the process of making it happen.
Thanks for the help!
Use datetime: https://docs.python.org/3/library/datetime.html
At a high level, I would start with initializing a datetime object with the first timestamp in your range, and a 1-second timedelta object.
import datetime
myDatetime = datetime.datetime(# TODO)
myTimedelta = datetime.timedelta(# TODO)
Then you could use a while loop and an endDatetime object with your last time in the range:
endDateTime = datetime.datetime(# TODO)
while myDatetime <= endDatetime:
print(myDatetime) # need to format it to look like your example
myDatetime = myDatetime + myTimedelta
Or you can calculate how many seconds are between the first and last end time and use a for loop:
seconds = # TODO
for i in range(seconds+1):
print(myDatetime + (i * myTimedelta))
Related
I'm trying to convert a whole column of timestamp values in UNIX format but I get some values that doesn't look like a normal timestamp format: 253402128000000
For what I know, a timestamp should look like: 1495245009655
I've tried in miliseconds, nanoseconds and other configurations for Pandas to_datetime but I haven't been able to find a solution that can convert the format.
EDIT
My data looks like below and the ValidEndDateTime seems way off.
"ValidStartDateTime": "/Date(1495245009655)/",
"ValidEndDateTime": "/Date(253402128000000)/",
SOLUTION
I've accepted the answer below because I can see the date is a "never-end" date as all the values in my dataset that can't be converted is set to the same value: 253402128000000
Thank you for the answers!
From a comment of yours:
The data I get looks like this: "ValidStartDateTime": "/Date(1495245009655)/", "ValidEndDateTime": "/Date(253402128000000)/",
The numbers appear to be UNIX timestamps in milliseconds and the big "End" one seems to mean "never end", note the special date:
1495245009655 = Sat May 20 2017 01:50:09
253402128000000 = Thu Dec 30 9999 00:00:00
Converted with https://currentmillis.com/
I think it was divided by 1,000,000 becoming 253402128 and calculated.
Which means approximately 44 years ago.
Format: Microseconds (1/1,000,000 second)
GMT: Wed Jan 11 1978 21:28:48 GMT+0000
I used this website as reference: https://www.unixtimestamp.com/
Use pd.to_datetime:
>>> pd.to_datetime(1495245009655, unit='ms')
Timestamp('2017-05-20 01:50:09.655000')
>>> pd.to_datetime(253402128000000 / 100, unit='ms')
Timestamp('2050-04-19 22:48:00')
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
I have a slack bot that gets schedule information and prints the start and end times of the user's schedule. I am trying to format the timestamp so that it is a more readable format. Is there a way to format this response?
Here is an example of the output:
co = get_co(command.split(' ')[1])
start = get_schedule(co['group'])['schedule']['schedule_layers'][0]['start']
end = get_schedule(co['group'])['schedule']['schedule_layers'][0]['end']
response = 'Start: {} \n End: {}'.format(start,end)
The current time format is 2019-06-28T15:12:49-04:00, but I want it to be something more readable like Fri Jun 28 15:12:49 2019
You can use dateparser to parse the date time string easily.
import dateparser
date = dateparser.parse('2019-06-28T15:12:49-04:00') # parses the date time string
print(date.strftime('%a %b %d %H:%m:%M %Y'))
# Fri Jun 28 15:06:12 2019
See this in action here
To convert timestamps of any format you can use the datetime module as described here:
https://stackabuse.com/converting-strings-to-datetime-in-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.
This question already has answers here:
Generate a list of datetimes between an interval
(5 answers)
Closed 8 years ago.
I have a starting date (lets say January 5th 2014) and an end date (lets say July 10th 2014). I know that an event occurs every Wednesday. Is there an easy way in Python to output all Wednesday with date between those date ranges?
So assuming January 7th is a Wednesday, then the code snippet would output 01.07.2014, 01.14.2014, 01.21.2014, and so on.
To get the first specific weekday after a given date, just add a timedelta of the difference in the weekdays:
wed = 2 # from the datetime.weekday definition
first_wed = start + datetime.timedelta(days=(7 + wed - start.weekday()) % 7)
Once you have that, please see Generate a list of datetimes between an interval in python.