How to get the current time as datetime

get current time python
python get current time in seconds
python get current timestamp
python get time difference
python get current hour
python datetime to string
python print(time elapsed)
python time difference

Just started with the playground. I'm trying to create a simple app.

I've created a date object like this:

var date = NSDate()

How can I get the current hour? In other languages I can do something like this:

var hour = date.hour

But I can't find any properties/methods like that. I've found a method, dateWithCalendarFormat. Should I use that? If so, HOW?

Update for Swift 3:

let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)

I do this:

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute

See the same question in objective-c How do I get hour and minutes from NSDate?

Compared to Nate’s answer, you’ll get numbers with this one, not strings… pick your choice!

How to get current date and time in Python?, Example 2: Current date in different formats. from datetime import date today = date.today() # dd/mm/YY d1 = today  The Get-Date cmdlet gets a DateTime object that represents the current date or a date that you specify. Get-Date can format the date and time in several .NET and UNIX formats. You can use Get-Date to generate a date or time character string, and then send the string to other cmdlets or programs. Get-Date uses the computer's culture settings to determine how the output is formatted. To view

How to get the current time in Python, Use: >>> import datetime >>> datetime.datetime.now() datetime.datetime(2009, 1 , 6, 15, 8, 24, 78915) >>> print(datetime.datetime.now()) 2009-01-06 15:08:  To display the current time without the date, click Format > Number > Time instead. You can customize your date or time formatting further by clicking Format > Number > More Formats > More Date and Time Formats. From here, you can customize the date and time formatting to use text, number, or additional characters like a forward slash.

You could also use NSDateFormatter's convenience method, e.g.,

func printTimestamp() {
  let timestamp = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .MediumStyle, timeStyle: .ShortStyle)
  print(timestamp)
}
printTimestamp() // Prints "Sep 9, 2014, 4:30 AM"

How to Get Current Date & Time in Python - TecAdmin, You can use now() function of datetime python module. This tutorial will show you various ways to get the current date and time in the python  from datetime import date today = date.today () print("Today's date:", today) Here, we imported the date class from the datetime module. Then, we used the date.today () method to get the current local date. By the way, date.today () returns a date object, which is assigned to the today variable in the above program.

Swift makes it really easy to create and use extensions. I create a sharedCode.swift file and put enums, extensions, and other fun stuff in it. I created a NSDate extension to add some typical functionality which is laborious and ugly to type over and over again:

extension NSDate
{
    func hour() -> Int
    {
        //Get Hour
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.Hour, fromDate: self)
        let hour = components.hour

        //Return Hour
        return hour
    }


    func minute() -> Int
    {
        //Get Minute
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.Minute, fromDate: self)
        let minute = components.minute

        //Return Minute
        return minute
    }

    func toShortTimeString() -> String
    {
        //Get Short Time String
        let formatter = NSDateFormatter()
        formatter.timeStyle = .ShortStyle
        let timeString = formatter.stringFromDate(self)

        //Return Short Time String
        return timeString
    }
}

using this extension you can now do something like:

        //Get Current Date
        let currentDate = NSDate()

        //Test Extensions in Log
        NSLog("(Current Hour = \(currentDate.hour())) (Current Minute = \(currentDate.minute())) (Current Short Time String = \(currentDate.toShortTimeString()))")

Which for 11:51 AM would write out:

(Current Hour = 11) (Current Minute = 51) (Current Short Time String = 11:51 AM)

Python: Display the current date and time, import datetime now = datetime.datetime.now() print ("Current date Previous: Write a Python program to get the Python version you are using. getHours () – Provides current hour between 0-23. getMinutes () – Provides current minutes between 0-59. getSeconds () – Provides current seconds between 0-59. 3.

Swift 2 answer :

 let date = NSDate()
 let calendar = NSCalendar.currentCalendar()
 let components = calendar.components([.Hour, .Minute], fromDate: date)
 let hour = components.hour
 let minutes = components.minute

How to Get the Current Date and Time in Python, Finally, we'll look at converting datetime objects to the popular Unix or Epoch timestamps. Getting the Current Date and Time with datetime. The  Actually, it's safer to set the current timezone set on the device with Time.getCurrentTimezone (), or else you will get the current time in UTC. Time today = new Time(Time.getCurrentTimezone()); today.setToNow(); Then, you can get all the date fields you want, like, for example:

How to Get Current Date and Time in Java, ZonedDateTime · Clock. LocalDate. LocalDate represents just a date, without time. This means that we can only get the  Get the current time either using std::time () or std::chrono::system_clock::now () (or another clock type ). std::put_time () (C++11) and strftime () (C) offer a lot of formatters to output those times. The sequence of the formatters matters: The formatters of strftime () are similar:

7.1. datetime — Basic date and time types, Whether a naive object represents Coordinated Universal Time (UTC), local time, For applications requiring aware objects, datetime and time objects have an  You should make a note on the fact that localtime() will return the current local time on the machine that runs the script and gmtime() will return the universal Greenwich Mean Time, or GMT (or UTC). Try the following example to print the current date and time but on GMT scale −

Get-Date, The Get-Date cmdlet gets a DateTime object that represents the current date or a date that you specify. Get-Date can format the date and time in several . Get Current Date & Time: java.time.LocalDateTime. The LocalDateTime.now () method returns the instance of LocalDateTime class. If we print the instance of LocalDateTime class, it prints current date and time both. System.out.println (java.time.LocalDateTime.now ()); System.out.println (java.time.LocalDateTime.now ());

Comments
  • Hello, thanks for answer, for example if minute is less than two character how can I return it with two characters like "04"
  • @YestayMuratov This handy webpage tells has all possible ways of formatting a date using the NSDateFormatter in Swift :) codingexplorer.com/…
  • It looks that the new Swift version (2) you have to use something similar to let components = calendar.components(.NSCalendarUnit.Year.union(NSCalendarUnit.Minute), fromDate: date), the vertical slash cant be used here anymore.
  • let components = calendar.components(NSCalendarUnit.Year.union(NSCalendarUnit.Minute), fromDate: date) removed the extra '.' before NSCalendarUnit
  • Swift 2.1: let components = calendar.components([ .Hour, .Minute, .Second], fromDate: date)
  • Creating an NSDateFormatter is expensive. You should create on and reuse it.
  • Swift 3: let timestamp = DateFormatter.localizedString(from: Date(), dateStyle: .short, timeStyle: .short)
  • interval is never used.
  • SaRaVaNaN DM's answer above had an extra '()' at the end of Calendar.current.
  • let calendar = Calendar.current; let unitFlags: Set<Calendar.Component> = Set<Calendar.Component ([.hour]); let components = calendar.dateComponents(unitFlags, from: self)
  • or even just Date().hour
  • @NoodleOfDeath sure. That depends if a reference to the date is needed or not.
  • Very true, and I suppose for all intensive purposes, you would want to use the same date variable when generating related date components rather than a newly generated one for each date component
  • no need to return an optional when getting something like year, month, day, etc... from a Date object. Btw Calendar component method is more appropriate for single component